JBd
JBd

Reputation: 115

:selected state on looped react component

I am basically wanting to do individual selected states on divs that I am rendering in a loop. I can only see a way to change the color of all of the rendered divs, but rather I wish to change the color of which ever one was clicked. Below is the code for the loop.

  renderSports() {
    const {sports} = this.props
    return sports.valueSeq().map(sport => this.renderActualSports(sport))
  },

  renderActualSports(sport) {
    const {sportCount} = this.props
    return (
      <div className="sportSeparator">
        {sport} {this.renderCount(sportCount.get(sport))}
      </div>
    )
  },

This will basically just render a list of some sports. I want to change the color of a selected sport on click.

Upvotes: 2

Views: 74

Answers (1)

klugjo
klugjo

Reputation: 20885

You will need to store the items that were clicked in your component state.

Assuming you would store this highlighted items in this.state.highlighted and that your sport variable is a string or number:

renderActualSports(sport) {
    const {sportCount} = this.props
    return (
      <div
        className="sportSeparator"
        onClick={this.highlight(sport)}
        style={{color: this.state.highlighted.indexOf(sport) > -1 && 'red' : ''}}
      >
        {sport} {this.renderCount(sportCount.get(sport))}
      </div>
    )
  },

  highlight(sport) {
    return () => {
      this.setState({highlighted: [...this.state.highlighted, sport]});
    }
  }

So what you are doing is onClick on the div you add that sport to the this.state.highlighted array and when displaying the list. you check if that sport is in the array and if yes you change the color using an inline style

Upvotes: 1

Related Questions