I'm working with a mapped array, assigning an 'active' class to an element when it's clicked (setting activeIndex
to the element's index).
But if an element's index is already the value of activeIndex
when it's clicked, I want to remove the 'active' class. Currently, when I click the same element a second time, the 'active' class is not removed.
class People extends Component {
state = {
people: [],
activeIndex: null,
};
personClickHandler = (index) => {
this.setState({activeIndex: index})
};
render() {
let people = this.state.people.map((person, index) => {
return (
<Person
name={person.name}
cat={person.cat}
key={index}
index={index}
active={this.state.activeIndex}
clicked={() => this.personClickHandler(index)} />
);
});
return (
<div className={classes.People}>
{people}
</div>
);
}
}
What I've tried:
I know I need to do some sort of state comparison. My initial thought was to compare the current value of activeIndex
with prevState.activeIndex
inside the click event handler, but I'm still running into the same issue, where the class never gets removed if the element is clicked a second time.
personClickHandler = (index) => {
this.setState(prevState => ({
activeIndex: (prevState.index !== index) ? index : null,
}));
this.setState({activeIndex: index})
};
What is the best approach for this?