1

i'm new on react and try to adding class based on array, but while i click in another button the active class should stay in the last button class when i click the other button, i don't have any clue to do so.

class Child extends React.Component {
  render(){
    return(
     <button
      onClick={this.props.onClick}
      className={`initClass ${this.props.isClass}`}>
      {this.props.text}
    </button>
   )
  }
}

class Parent extends React.Component {
 constructor(props) {
    super(props);
     this.state = {
      newClass: null,
     };
  }

  myArray(){
    return [
     "Button 1",
     "Button 2",
     "Button 3"
   ];
  }

  handleClick (myIndex,e) {
   this.setState({
     newClass: myIndex,
    });
  }

  render () {
    return (
      <div>
       {this.myArray().map((obj, index) => {
         const ifClass = this.state.newClass === index ? 'active' : '';
         return <Child
           text={obj}
           isClass={ifClass}
           key={index}
           onClick={(e) => this.handleClick(index,e)} />
       })}
     </div>
   )
  }
}

ReactDOM.render(<Parent/>, document.querySelector('.content'));
.active {
  background: cyan;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>

<div class='content'/>

1
  • 1
    Note, I have added a dummy markup and css to make the code runnable, so everyone can test. It was not a part of original post. Commented Nov 24, 2017 at 5:28

1 Answer 1

1

Make your newClass an array and while putting the class check if that index exists in your state array.

constructor(props) {
  super(props);
   this.state = {
    newClass: [],    //an array
   };
}

....

handleClick (myIndex,e) {
 if(!this.state.newClass.includes(myIndex)){
     this.setState({
        newClass: [...this.state.newClass, myIndex],
     });
 }
}

....

render () {
    const that = this;

    return (
        <div>
            {this.myArray().map((obj, index) => {
                const ifClass = that.state.newClass.includes(index) ? 'active' : '';
                return <Child
                          text={obj}
                          isClass={ifClass}
                          key={index}
                          onClick={(e) => that.handleClick(index,e)} />
            })}
       </div>
    )
  }

  ....

As you haven't told when you need to remove the class, so not adding the step where you should extract some index from the array.

Sign up to request clarification or add additional context in comments.

3 Comments

Please note, you can use SO snippet to make your code testable. For react, make sure to use babel checkbox.
But sometimes you just want to give an idea to the user and not the whole implementation
Cool! , Thanks @AjayGaur

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.