5

How do you add a CSS class to an existing REACT element on click?

I have a JSFiddle created: https://jsfiddle.net/5r25psub/

In the fiddle, the code only works if I have the statement: this.setState({color:blue});

I want something like this.setState({className: 'green'}); What am I doing wrong?

Code:

    <html>
    <script>
        var Hello = React.createClass({
            getInitialState: function(){
                return {
                    color: 'blue'
                };
            },
            handleClick: function(){
                if (this.state.color === 'blue'){
                    this.setState({className = " green"});
                } else {
                    this.setState({color: 'blue'});
                }
            },
            render: function() {
                return <button className={this.state.className} onClick={this.handleClick}>My background is: {this.state.color}, Click me to change</button>;
            }
        });

        React.render(<Hello name="World" />, document.getElementById('container'));

    </script>
    <body>
    <script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<style>
.green {
    background-color: lightgreen;
}

.blue {
    background-color: lightblue;
}
</style>

    <div id="container">
        <!-- This element's contents will be replaced with your component. -->
    </div>
    </body>
    </html>
1
  • 1
    Inside handleClick you wrote className = " green" but it should be className: "green" Commented Jun 24, 2016 at 0:39

4 Answers 4

4

You can use the module classnames found here:

https://www.npmjs.com/package/classnames

So you would do something like:

getClassNames() {
    return classNames({
        'blue':  this.state.clicked,
        'green':  !this.state.clicked
    });
},
render () {
    return <button className={this.getClassNames()} onClick={this.setState({clicked: !this.state.clicked})>
}
Sign up to request clarification or add additional context in comments.

1 Comment

nice, didnt know about that, always just coded that in myself, prob still will though. lol
1

You need to add all state parameters to getInitialState, right now the only thing you have is color, so this.state.color is the only thing in there

When you set your state to className: something, that is the only thing in there now, even color is gone...and that is why the initial color is the normal bland gray

you have a syntax error in setState as well, its not

this.setState({className = " green"});

It should be:

this.setState({className: " green"});

Finally, React.render is deprecated, you need to use ReactDOM.render now

Fiddle: https://jsfiddle.net/omarjmh/69z2wepo/36597/

2 Comments

I am a bit confused on how do I retrieve the classList. Does element.getClassList() work in React? Or is there an other way to do so ?
why do you need a class list? Take a look at the code in the fiddle I posted, you had the incorrect external resources, open up the console and see what it says, thats all it took for me to answer your question
0

https://jsfiddle.net/ajvf50s6/3/

Most probably, you should better do a verification based on the className, not on the color state property:

handleClick: function(){
    if (this.state.className === 'blue'){
        this.setState({className: "green"});
    } else {
        this.setState({className: "blue"});
    }
}

Also, as @Omarjmh mentioned, you have a typo in your code. {className = " green"} is wrong assignment.

2 Comments

Perfect! This definitely helps. I had a followup question - How do I add a css class to an existing element which already has classes. For example, an element <div class="green"></div> , I would like to add the class centre_align to it such that it now looks: <div class="green centre_align"> </div> Is that possible ?
Also, this is one for single element. would it be necessary to preserve states for multiple elements?
0

Rather than using two state variables, you can do like this.

Since the initial state of color is blue, you can change the handleClick function as :

handleClick: function(){
 if (this.state.color === 'blue'){
  this.setState({color : "green"});
 } else {
   this.setState({color: 'blue'});
 }
}

And, for the className, consider a variable :

let colorClass= this.state.color === "blue" ? "blue" : "green" 

Now, replace the className as below and you need to enclose that object where you call div class.

return <button className={colorClass} onClick={this.handleClick}>My background is: {this.state.color}, Click me to change</button>;

I hope it works fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.