Hey, what is the idiomatic way to add and remove a...
# compose-web
a
Hey, what is the idiomatic way to add and remove a class to an element using a
mutableState<Boolean>
? For now I have this but it's very ugly I guess 👀
Copy code
data class Tab(val name: String, val link: String, val selected: MutableState<Boolean> = mutableStateOf(false)) 

@Composable
fun Tab(tab: Tab) {
	NavLink(tab.link, {
		if (tab.selected.value) {
			ref { htmlAnchorElement ->
				htmlAnchorElement.classList.add("selected")
				onDispose {}
			}
		} else {
			ref { htmlAnchorElement ->
				htmlAnchorElement.classList.remove("selected")
				onDispose {}
			}
		}
	}) {
		Text(tab.name)
	}
}
b
classes is cumulative and reproducaeble. So a good old if statement whith classes() invocation is sufficient attrs = { classes("other-class") if(selected) classes("selected") }
a
aah it works like that, I see, thanks !
b
Yep, quite elegant
h
BTW are you using NavLink from routing compose? How do you set
selected
? routing compose already parses the current path and sets the
active
class. But I guess, it should be better to provide a Boolean in the attrs block to set the classes by yourself
Eg:
Copy code
NavLink(tab.link, { selected ->
  if (selected) {
    classes("selected")
  }
}) {
  Text(tab.name)
}
a
Yeah I've seen later that there was already an
active
class set by routing-compose, so I used it in the end
h
Yeah, but I removed the default hardcoded class and added the Boolean parameter, because a library should support customizing 🙂 Published in 0.2.6
a
Oh it's you, so I'll change my code like your example 🙂