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 ?
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 ?
You can use the style attribute.
<SomeComponent style={{
backgroundColor: someCondition ? 'purple' : null
}} />
Considering paragraph element
document.getElementsByClassName("container").style.color = "blue";
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>;
}