Hey folks, I'm trying to modify the generated <.table> component in Phoenix LiveView to allow selecting rows (see screenshot). But, given I'll need to, say, add a class to the <tr> if the row is selected, I presume that will require some local state for the component. Do I have to make the leap to a LiveComponent for it? Or is there some other way to have basic state for something like this?
#Would selectable table rows require a LiveComponent?
1 messages · Page 1 of 1 (latest)
CSS allows styling based on sibling state and parent state, but in this case you have a checkbox as a child of the tr and you want to style it, so this would be styling based on child state. Not sure CSS supports that... so yes it seems like the only way might be to keep some local state per row. Kind of unfortunate, I would really try and find a way to do it purely in CSS, but it might not be possible
wait, this might actually be possible now
lol, ok, I was trying this out until I realized it's supported in all major browsers except firefox, which is what I'm running 😅
anyway, here's the punchline: the only way you can make this work with pure CSS is using the :has selector, which is brand new: https://developer.mozilla.org/en-US/docs/Web/CSS/:has
The functional :has() CSS pseudo-class represents an element if any of the relative selectors that are passed as an argument match at least one element when anchored against this element. This pseudo-class presents a way of selecting a parent element or a previous sibling element with respect to a reference element by taking a relative selector ...
and is not currently supported by Firefix, but is supported by all other major browsers: https://caniuse.com/css-has
Yeah I tried with sibling selectors but the dom structure isn’t quite right for it
yep
if you instead stop using a table and use divs in a css grid then maybe you could make it work with the sibling selector
Yeah, possibly. But hopefully switching to a live component won’t create so much friction that I’d reach that far. Good thinking though.
the downside is having to have server-client roundtrips just to update some styling, on slower connections you'll see a visual delay
I suppose I could squeeze in a bit of htmx or alpine. But that does break the model a bit.
LiveView has JS commands to change classes that don't require a trip to the server.
@waxen yew Thanks! Didn't realise that. Having looked into it now, though, it doesn't look like there's an easy way to toggle classes, or set them based on the value of the checkbox's change event 🤔