Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change active element in a list using react

I have a list of elements created by using an array in react. On user click how can I make the clicked element active (by adding a CSS class) while making the other elements inactive (by removing the active class)?

My rendering of elements looks like this.

   {this.props.people.map(function(person, i){
        <div className='media' key={i} onClick={state.handleClick.bind(state,i,state.props)}>
          <item className="media-body">{person.name}</item>
        </div>
    }

When the user clicks on one of these elements an active class will be added to the clicked 'media' element making the clicked element 'media active' while removing the 'active' class from the previously clicked element??

like image 630
rksh Avatar asked Nov 24 '16 17:11

rksh


1 Answers

  constructor(props) {
    super(props);
    this.state = { activeIndex: 0 };
  }

  handleClick(index, props) {
    // do something with props
    // ...    

    // now update activeIndex
    this.setState({ activeIndex: index });
  }

  render() {
    return (
      <div>
        {
          this.props.people.map(function(person, index) {
            const className = this.state.activeIndex === index ? 'media active' : 'media';  
            return (
              <div className={className} key={index} onClick={handleClick.bind(this, index, this.props)}>
                <item className="media-body">{person.name}</item>
              </div>
            );
          }, this)
        }
      </div>
    );
  }
like image 167
yadhu Avatar answered Oct 29 '22 12:10

yadhu