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"
        }
      };

2 Answers 2

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'})
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.