Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

People also ask

Can I use hover in inline CSS?

Short answer: you can't. Long answer: you shouldn't. Give it a class name or an id and use stylesheets to apply the style. :hover is a pseudo-selector and, for CSS, only has meaning within the style sheet.

How do you hover in React?

To add a hover button in React, we can add a button that has the onMouseOver and onMouseOut props set to functions that run when we move our mouse over the button and move our mouse outside of it respectively. In the functions, we set a state to track whether we hovered over the button or not.

Can We Use inline CSS in React?

In React, inline styles are not specified as a string. The style attribute accepts a JavaScript object with camelCased properties. Below are the basic steps for defining inline CSS: 1. Change the CSS property name to its camelCase version like "background-color" to "backgroundColor", "font-size" to "fontSize", etc.

How do you add inline styles to a React?

To set inline styles in React: Set the style prop on the element to an object. Set the specific CSS properties and values to style the element. For example, <div style={{backgroundColor: 'salmon', color: 'white'}}> .


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'}
    }
    return(
      <div>
        <a style={linkStyle} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
      </div>
    )
}

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


Late to party but come with solution. You can use "&" to defines styles for hover nth Child etc:

day: {
    display: "flex",
    flex: "1",
    justifyContent: "center",
    alignItems: "center",
    width: "50px",
    height: "50px",
    transition: "all 0.2s",
    borderLeft: "solid 1px #cccccc",

    "&:hover": {
      background: "#efefef"
    },
    "&:last-child": {
      borderRight: "solid 1px #cccccc"
    }
},

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


You can use Radium - it is an open source tool for inline styles with ReactJS. It adds exactly the selectors you need. Very popular, check it out - Radium on npm


Here's my solution using React Hooks. It combines the spread operator and the ternary operator.

style.js

export default {
  normal:{
    background: 'purple',
    color: '#ffffff'
  },
  hover: {
    background: 'red'
  }
}

Button.js

import React, {useState} from 'react';
import style from './style.js'

function Button(){

  const [hover, setHover] = useState(false);

  return(
    <button
      onMouseEnter={()=>{
        setHover(true);
      }}
      onMouseLeave={()=>{
        setHover(false);
      }}
      style={{
        ...style.normal,
        ...(hover ? style.hover : null)
      }}>

        MyButtonText

    </button>
  )
}

Full CSS support is exactly the reason this huge amount of CSSinJS libraries, to do this efficiently, you need to generate actual CSS, not inline styles. Also inline styles are much slower in react in a bigger system. Disclaimer - I maintain JSS.