Add & Remove CSS classes with React

css, html, javascript, react-native, reactjs

Solution

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.

Problem

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.

Original source

Related problems