fhucho fhucho - 3 months ago 35
React JSX Question

Inline CSS styles in React: how to implement a:hover?

I quite like the inline CSS pattern in React and decided to use it.

However, you can't use the :hover and similar selectors. So what's the best way to implement highlight-on-hover while using inline CSS styles?

One suggestion from #reactjs is to have a

Clickable
component and use it like this:

<Clickable>
<Link />
</Clickable>


The
Clickable
has a
hovered
state and passes it as props to the Link. However, the
Clickable
(the way I implemented it) wraps the
Link
in a
div
so that it can set
onMouseEnter
and
onMouseLeave
to it. This makes things a bit complicated though (e.g.
span
wrapped in a
div
behaves differently than
span
).

Is there a simpler way?

Answer

I'm in the same situation. Really like the pattern of keeping the styling in the components but the hover states seems like the last hurdle.

What I did was writing a mixin that you can add to your component that needs hover states. This mixin will add a new hovered property to the state of your component. It will be set to true if the user hovers over the main DOM node of the component and sets it back to false if the users leaves the element.

Now in your component render function you can do something like:

<button style={m(
        this.styles.container,
        this.state.hovered && this.styles.hover,
      )}>{this.props.children}</button>

Now each time the state of the hovered state changes the component will rerender.

I've also create a sandbox repo for this that I use to test some of these patterns myself. Check it out if you want to see an example of my implementation.

https://github.com/Sitebase/cssinjs/tree/feature-interaction-mixin