How to modify CSS using JavaScript in React.js

Viewed 731

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 ?

4 Answers

You can use the style attribute.

<SomeComponent style={{
    backgroundColor: someCondition ? 'purple' : null
}} />

Considering paragraph element

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

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>

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