Pietro Coelho
Pietro Coelho

Reputation: 2072

How to toggle an active class on list items?

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?

Upvotes: 3

Views: 2309

Answers (1)

GG.
GG.

Reputation: 21884

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>
    )
  }
}

Upvotes: 4

Related Questions