Reputation: 115
I'm creating a chat app, and I want to list all of the chatrooms listed in the data with a map function. When the user selects a certain room from the list, the main page updates to show the messages for the selected room.
I'm having issues using the created button's id for its onClick event. I've tried using this
, this.id
, and even the index provided in the map function because the id's are the same as the indexes; however, my setSelectedRoom doesn't seem to like the function.
i
should work, but I get the error of 'Too many re-renders'. I'm not entirely sure how to get past this issue. Any ideas?
The map function is necessary so that the page can update when new chatrooms are added, so how do I avoid the 'Too many re-renders' error?
{props.chatData.map((val, i) => {
return (
<Button className={`room-${i}`} id={i} onClick={setSelectedRoom(i)}>#{val.name}</Button>
)
})}
Upvotes: 0
Views: 59
Reputation: 4913
I could give you an idea. Try something like this,
{
props.chatData.map((val, i) => {
return (
<Button className={`room-${i}`} id={i} onClick={() => setSelectedRoom(i)}>
#{val.name}
</Button>
);
});
}
also, I think id
is a HTML props and we cannot access it. Try using other names like chatID
and you can access it through this.props.chatID
.
JSX Expression is executed immediately, so whenever it renders, it calls itself infinite times. That's why wrap it with another function.
Upvotes: 1