Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle css class of a single element in a .map() function in React

I have a .map() function where I'm iterating over an array and rendering elements, like so:

      {options.map((option, i) => (
        <TachyonsSimpleSelectOption
          options={options[i]}
          key={i}
          onClick={() => this.isSelected(i)}
          selected={this.toggleStyles("item")}
        />

I am toggling the state of a selected element like so:

isSelected (i) {
    this.setState({ selected: !this.state.selected }, () => { console.log(this.state.selected) })
}

Using a switch statement to change the styles:

  toggleStyles(el) {
    switch (el) {
      case "item":
        return this.state.selected ? "bg-light-gray" : "";
        break;
    }
  }

And then passing it in my toggleStyles method as props to the className of the TachyonsSimpleSelectOption Component.

Problem

The class is being toggled for all items in the array, but I only want to target the currently clicked item.

Link to Sandbox.

What am I doing wrong here?

like image 732
A7DC Avatar asked Mar 14 '18 03:03

A7DC


1 Answers

You're using the selected state incorrectly.

In your code, to determine whether it is selected or not, you depends on that state, but you didn't specify which items that is currently selected.

Instead saving a boolean state, you can store which index is currently selected so that only specified item is affected.

This may be a rough answer, but I hope I can give you some ideas.

on your render:

{options.map((option, i) => (
  <TachyonsSimpleSelectOption
    options={options[i]}
    key={i}
    onClick={() => this.setState({ selectedItem: i })}
    selected={this.determineItemStyle(i)}
   />
))}

on the function that will determine the selected props value:

determineItemStyle(i) {
  const isItemSelected = this.state.selectedItem === i;
  return isItemSelected ? "bg-light-gray" : "";
}

Hope this answer will give you some eureka moment

like image 187
Dimitrij Agal Avatar answered Nov 15 '22 13:11

Dimitrij Agal