0

I'm creating a button with React.createElement:

React.createElement('button', {style: button.key === this.state.customBtnSelected ? customBtnSelected : customBtnUnSelected, onClick: () => {this.handleCustomBtnClick(i)} }, button.label)

So the one of the css styles is in the customBtnUnSelected variable.

But how do I add css classes for the hover state? So far this isn't working:

       const customBtnUnSelected = {
        padding: 12,
        textAlign: "center",
        textDecoration: "none",
        display: "inline-block",
        fontSize: 12, 
        cursor: "pointer",
        backgroundColor: "#CFD4DA",
        border: "1px solid white",
        &:hover: {
          color: "#fff"
        }
      };
NewToJS
  • 2,011
  • 4
  • 35
  • 62

2 Answers2

1

It's not possible to use the :hover, :after, or :before styling to an element, using inline styling.

The only way to achieve that is to use the <style> tag, or linking an external CSS file to your project.

To insert a style tag, you just place it somewhere in your app. It may be in one of your components, or in the root HTMl file, etc...

return (
  <style>{`
    .myButton {
      padding: 8;
      background: black
    }
    .myButton:hover {
      background: grey
    }
  `}</style>
)

Then, you can just use the myButton class on the className prop of your button.

<button className='myButton'>Click</button>

or

React.createElement('button', {className: 'myButton'})
river737
  • 89
  • 5
0

Regardless of using React.createElement or the JSX syntax, React doesn't support selecting pseudo elements with inline styling.

This question has a few answers with a lot more tips that might help you: CSS pseudo elements in React

Thalles Cezar
  • 169
  • 1
  • 4