Hello everyone, I am stumped trying to find a way to change the css class of an element in react.
I am coming from Jquery where i would just write $(‘example’).css("")
I tried setting a const like this
const divStyle = {
color: 'blue',
};
And then adding a onClick={this.divStyle} to the element. However that didn’t work
I feel like I am very close, however google is giving me lots of complicated answers that I don’t really understand. I would appreciate an expert’s help on this.
Wow! That’s a lot more complex than Jquery.
This may sound like a stupid question, but how would you do something like change the color or the font-size?
The code above assumes you have a CSS box class defined in a CSS file or style element.
.box {
width: 200px;
height: 200px;
}
The box color starts with the color ‘red’ defined by the boxColor state property. When the button is clicked, a random color is selected from the colors array which is not the current color of the boxColor state property. This makes sure the box will always change to a different color when the button is clicked.
It’s a shift in mentality:
often with JQuery I end up being imperative: you are now red.
while with React I tend to be state driven: everything that has this state is now red.
the drawback is that it requires you to think a little bit in advance about your app, but tend to be more scalable and maintainable in the long run.
Like any other css properties.
But remember that
The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes. For example:
meaning that the css property font-size in JSX will be fontSize