Home > Blockchain >  onClick() color change for item in mapped list not working
onClick() color change for item in mapped list not working

Time:12-11

I have a list of items that are displayed on the UI in a React class component. Whatever item the user clicks on should turn green, while the rest are gray. I also want each item to have a hover color of green.

What I currently have is not working. If I click on one list item, ALL the list items turn green. Then, if I click another list item, all revert back to grey.

JS:

class AFile extends Component {
    constructor(props) {
      super(props);
      this.state = {
        selected: false
      }
    }

  handleClick= (index) => {
   // do stuff with index
   this.setState(selected: !this.state.selected);
  }

  const list = [
    {order: 1, name: 'a'}, 
    {order: 2, name: 'b'}, 
    {order: 3, name: 'c'}
  ]
  render() {
    return (    
     list.map( (item, index) => {
       return (
         <div key={index}>
           <Link to='#' onClick={()=>this.handleClick(index)} className={ this.state.selected ? 'list-item-selected' : 'list-item }  >
             {item.order}. {item.name}
           </Link>
         </div>
       )
     }
   )
 }
}

CSS:

.list-item {
  color: gray;
}
.list-item:hover {
  color: green;
}
.list-item-selected {
  color: green;
}

CodePudding user response:

You should store the selected item in the state. Try this:

class AFile extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItem: null,
    };
  }

  handleClick = (selectedItem) => {
    this.setState({ selectedItem });
  };

  render() {
    const list = [
      { order: 1, name: 'a' },
      { order: 2, name: 'b' },
      { order: 3, name: 'c' },
    ];

    return list.map((item, index) => {
      return (
        <div key={index}>
          <Link
            to="#"
            onClick={() => this.handleClick(item)}
            className={
              this.state.selectedItem?.name === item.name
                ? 'list-item-selected'
                : 'list-item'
            }
          >
            {item.order}. {item.name}
          </Link>
        </div>
      );
    });
  }
}

Or you can store selected name

  • Related