Answer the question
In order to leave comments, you need to log in
React.js: how to add a class to an element on click?
There is this code:
crateDropDownList: function () {
var dropDownBrandClass = this.state.checkedBrand ? 'active' : '';
return ['a', 'b', 'c'].map(function (item, i) {
return <li className={dropDownBrandClass} onClick={this.checkBrand.bind(this, item)} key={i}><a href="#">{item}</a></li>
}.bind(this));
},
getInitialState: function () {
return {
checkedBrand: false
}
},
checkBrand: function (event) {
this.setState({
checkedBrand: !this.state.checkedBrand
});
},
Answer the question
In order to leave comments, you need to log in
The problem is that the class name and state in your case are applied inside the component. And all this should be inside the list element. To make the code above work, you need to move the elements of the list into separate components. Or, another solution is to store an array of flags for each element in the checkedBrand state, and switch these flags on click and substitute classes based on them.
This question is not related to js or react. This is an architectural error. And the fact that you don’t see it yourself suggests that it will be most useful for you to read some cool and fundamental books about OOP right now.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question