Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How do you set an active state on one component at a time, and remove the active state on all others in React?

I have a basic application, where I click on a dot and it changes the colour to red. I have two dots. However, I want to be able to click on one, give it its active state, then disable the active state the other dot. Currently, I have it working. However, I don't feel confident its the right approach.

In the Dot component, I have logic to set an 'activeDot' class

className={"dot " + (this.props.isActive ? "activeDot" : "")}

I have a function in the main parent component 'handleDot'

handleDot = id => {
    var state = Object.assign({}, this.state);
    for (let i = 0; i < this.state.dots.length; i++) {
      if (i === id) {
        state.dots[i].isActive = true;
      } else {
        state.dots[i].isActive = false;
      }
    }
    this.setState(state);
  };

Here is a link to the project

https://codesandbox.io/s/sad-grothendieck-1q319

is there a better way to approach this?

Thanks in advance

1 Answer

solution:

  handleDot = id => {
    this.setState(prevState => ({
      dots: prevState.dots.map((dot, i) => ({
        ...dot,
        isActive: i === id
      }))
    }));
  };