Add & Remove CSS classes with React
Solution 1
In react when state changes react re-renders. In your case if you want to change the way something looks then you probably want to force another render. What you can do is have the className
be part of state and then update the state when you want, causing the component to re-render with the new className
. For example:
constructor() {
super();
this.state = {
className: 'btn'
}
}
render () {
return (
<Button className={this.state.className}>Click me</Button>
)
}
Since the className
is bound to state updating state will cause the button to render again with the new className
. This can be done like this:
updateClass() {
let className = this.state.className;
className = className + ' ' + 'btn-primary'
this.setState({className})
}
This is an example of the function you can call on the click of a button and update the className
for the button.
Solution 2
There's a nice utility you can use for classname logic + joining classNames together
https://github.com/JedWatson/classnames
Based on setting React state for active you could do something like the following. You can get as complex as you need to with the logic. If the logic result is falsy, that key won't be included in the output.
var classNames = require('classnames');
var Button = React.createClass({
// ...
render () {
var btnClass = classNames({
btn: true,
'btn-active': this.state.isActive
});
return <button className={btnClass}>{this.props.label}</button>;
}
});
George Welder
Updated on June 19, 2022Comments
-
George Welder almost 2 years
I am new to React. I have a few buttons in a button group:
<div className="btn-group"> <button className="btn btn-mini btn-default" onClick={() => this.changeDataType("type1")} >Button1</button> <button className="btn btn-mini btn-default" onClick={() => this.changeDataType("type2")} >Button2</button> <button className="btn btn-mini btn-default" onClick={() => this.changeDataType("type3")} >Button3</button> </div>
Whenever the user clicks on one of the buttons, this button should become the active, selected one. I found out that I need to add the CSS class
active
to the corresponding button, but I am not sure how to implement this.I thought about this for a bit. I have a
changeDataType
function connected to my buttons, in which I do some other stuff. Would I then, in there, somehow manipulate the CSS?So I guess my questions are first, how to target the button I need to target, and second, how I could change that button's CSS with React.