How to toggle an active class on list items?

All we need is an easy explanation of the problem, so here it is.

I’m having a issue in trying to implement a basic functionality in React. I have a list of <img>, and when I click in one, I want to add an active class to this img and remove this class from the other images.

class DefaultImages extends React.Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(e) {
    console.log("Element:", e.target)
    // I can add the class here, but where to remove from the other images?
  }

  render() {
    var imgSize = "100"
    return (
      <div>
        <img onClick={this.handleClick} src="img/demo.png" width={imgSize} height={imgSize} />
        <img onClick={this.handleClick} src="img/demo2.png" width={imgSize} height={imgSize} />
        <img onClick={this.handleClick} src="img/demo3.jpg" width={imgSize} height={imgSize} />
        <img onClick={this.handleClick} src="img/demo4.png" width={imgSize} height={imgSize} />
      </div>
    )
  }
}

I know how to toggle the class from the clicked image, but how can I remove the active class from the siblings images?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Use the component’s state to store the active item and rerender the view when it changes:

import React, { Component } from 'react'

const IMG_SIZE = 100
const imgs = [{ id: 1, src: 'img/demo.png' }, { id: 2, src: '...' }, etc]

class DefaultImages extends Component {
  constructor() {
    this.state = { activeItem: {} }
    this.toggleActiveItem = this.toggleActiveItem.bind(this)
  }

  toggleActiveItem(imgId) {
    this.setState({ activeItem: { [imgId]: true } })
  }

  render() {
    return (
      <div>
        {imgs.map(img =>
          <img
            className={this.state.activeItem[img.id] ? 'active' : ''}
            onClick={e => this.toggleActiveItem(img.id)}
            src={img.src}
            width={IMG_SIZE}
            height={IMG_SIZE}
            alt={`Default image ${img.id}`}
          />
        )}
      </div>
    )
  }
}

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply