I
I
Isaac Clark2015-10-07 18:14:58
JavaScript
Isaac Clark, 2015-10-07 18:14:58

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));
},

here I create a menu of three elements, now when I click on one of the elements, I want to add a class to the item that I clicked on.
getInitialState: function () {
    return {
        checkedBrand: false
    }
},

checkBrand: function (event) {
    this.setState({
        checkedBrand: !this.state.checkedBrand
    });

},

But the problem is that the class is added to all menu items. Can you please tell me how to add a class to exactly the point where the event occurred?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
whogood, 2015-10-07
@Dark_Knight

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.

A
Anton Zhukov, 2015-10-07
@MrCheater

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.

M
mrak4, 2019-05-30
@mrak4

What does OOP have to do with the react architecture if it is more functional in itself.
PS I do not argue the architecture is not good, but do not confuse beginners

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question