Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  156] [ 6]  / answers: 1 / hits: 150689  / 9 Years ago, thu, february 26, 2015, 12:00:00

I am quite new to React and I am struggling a little with converting my thinking from standard js.



In my react component I have the following element:



<div className='base-state' onClick={this.handleClick}>click here</div>


The behaviour I am looking for is to add an extra class on click. My first idea was to try and add the class in the click handler function e.g.



handleClick : function(e) {
<add class click-state here>
}


I haven't been able to find any examples that do anything similar though, so I am fairly sure I am not thinking about this in the right way.



Can anyone point me in the right direction?


More From » node.js

 Answers
3

The list of classes can be derive from the state of the component. For example:



var Component = React.createClass({
getInitialState: function() {
return {
clicked: false
};
},

handleClick: function() {
this.setState({clicked: true});
},

render: function() {
var className = this.state.clicked ? 'click-state' : 'base-state';
return <div className={className} onClick={this.handleClick}>click here</div>;
}
});


Calling this.setState will trigger a rerender of the component.


[#67667] Tuesday, February 24, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
albert

Total Points: 652
Total Questions: 105
Total Answers: 108

Location: Pitcairn Islands
Member since Fri, Oct 15, 2021
3 Years ago
;