Reactjs – 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:

    <Link />

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?

Best Answer

I think onMouseEnter and onMouseLeave are the ways to go, but I don't see the need for an additional wrapper component. Here is how I implemented it:

var Link = React.createClass({
  getInitialState: function(){
    return {hover: false}
  toggleHover: function(){
    this.setState({hover: !this.state.hover})
  render: function() {
    var linkStyle;
    if (this.state.hover) {
      linkStyle = {backgroundColor: 'red'}
    } else {
      linkStyle = {backgroundColor: 'blue'}
        <a style={linkStyle} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>

You can then use the state of hover (true/false) to change the style of the link.

Related Question