2

How can I change the css styles using JavaScript on React ?

For example I would make this:


document.querySelector('.container').style.backGroundColor='purple';

}

Is it right ? Or should i make it with another way ?

1
  • Which way did you follow for your CSS in React? Commented Sep 13, 2020 at 16:57

4 Answers 4

2

You can use the style attribute.

<SomeComponent style={{
    backgroundColor: someCondition ? 'purple' : null
}} />
Sign up to request clarification or add additional context in comments.

1 Comment

Avoid inline styles like the plague. Seems like a good idea at the time but down the road becomes very difficult to maintain
0

Considering paragraph element

document.getElementsByClassName("container").style.color = "blue";

3 Comments

This is a very imperative way of doing it which contradicts with React.
@StefanBajić can you please elaborate a little bit how would it contradict with React?
I think your code will break after component's next render
0

The simple way to change css in Reactjs is Inline styling. Others way you can see at: https://codeburst.io/4-four-ways-to-style-react-components-ac6f323da822

Let example. If your want change color of user status. Active will be green or deactive will be red.

const Example = (props) => {
    let isActive = Math.floor(Math.random() * 2) % 2 === 0;
    const color = isActive ? 'green' : 'red';

    return <div style={{backgroundColor: color}}> {isActive ? 'Active' : 'Deactive'} </div>;
}

OR:

const Example = (props) => {
    let isActive = Math.floor(Math.random() * 2) % 2 === 0;
    
    return <div style={{backgroundColor: isActive ? 'green' : 'red'}}> {isActive ? 'Active' : 'Deactive'} </div>;
}

OR all styling:

const Example = (props) => {
    let isActive = Math.floor(Math.random() * 2) % 2 === 0;
    let styleStatus = isActive ?
        {
            backgroundColor: 'green',
            fontSize: '20',
        } :
        {
            backgroundColor: 'red',
            fontSize: '15',
        };

    return <div style={styleStatus}> {isActive ? 'Active' : 'Deactive'} </div>;
}

Comments

0

make a const type obj like this(must create inside render method)

const mystyle = {
      color: "white",
      backgroundColor: "DodgerBlue",
      padding: "10px",
      fontFamily: "Arial"
    };

and assign this into your element like this

h1 style={mystyle}>Hello Style!</h1>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.