Hi, I am testing the map method in a simple React application and I am stuck with a propagation problem. The code is very simple: I have a render method:
<div className={styles.tagContainer}>
{ this.state.items.map((item, key) => {
return (
<div key={key} onClick={(e) => {this.onClickTag(e, item); return false;}}>
<p className={`${this.state.active !== true ? styles.tagNormalState : styles.tagSelectedState}`}>{item.Title}</p>
</div>
);
})}
</div>
This method is rendering a serie of div elements with styled p-elements. The div element has an onClick event that when clicked it shoul call another method called onClickTag which is this:
private onClickTag(e: React.MouseEvent<HTMLElement>,item): any {
e.stopPropagation();
this.setState({
active: true
});
}
right now this method only shange the state to set another color to the div-element when is clicked. The problem is that is not just the clicked element that get the new color but all the items. I tryed to use the e.stopPropagation() to stop this but is not working. Do you any idea what the problem can be? Best regads Americo
HI, I managed to resolve by updating this line:
onClick={(e) => {this.onClickTag(e, item); return false;}}
Now it is working!
Samurai Kid 2019
Fullstack Engineer
Can you copy all your components code lines because it's not clear to me how exactly your code looks like and what might cause the problem.
However, what I think the problem is how you control or save the state of your component.
I wrote an example of how I would do that. Feel free to let me know if that's what you meant or I am missing something.
codesandbox.io/s/0pmkyy0jmw
In addition, I believe
e.stopPropagation()stops the event to bubble up in the chain but once you change the state the components that are listening to that state will be rendered. Thus, I think the problem is how you handle or structure your state.