rksh rksh - 8 days ago 5
React JSX Question

Change active element in a list using react

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

My rendering of elemetns 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>
}


On user click of 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??

Answer
  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>
    );
  }
Comments