Kevin Kevin - 2 months ago 12
Javascript Question

Add a unique key to dynamic children without having any unique key

I'm mapping some arrays in a React project and I return li-tag children, of course React expects a unique key for every dynamic child. However, I don't think I have any unique key... At least, not that I know of. With my data and code (being fetched from https://tmi.twitch.tv/group/user/instak/chatters), is there any key i can pass?

import React, {Component} from 'react';

export default class Overview extends Component{
constructor(props, context){
super(props, context);
this.state = {
chatters: {
moderators: [],
staff: [],
admins: [],
global_mods: [],
viewers: []
}
};
}

componentWillMount() {
fetch('/api/overview') // fetch from Express.js server
.then(response => response.json())
.then(result => this.setState({
chatters: result.chatters
}));
}

render(){
let {chatters} = this.state;
return (
<div>
<h2>Chatters</h2>
<div>
<h3>Moderators</h3>
<ul>
{chatters.moderators.map(chatter => {
return <li key={chatter.key}>{chatter}</li>;
})}
</ul>
</div>
<div>
<h3>Staff</h3>
<ul>
{chatters.staff.map(chatter => {
return <li key={chatter.key}>{chatter}</li>;
})}
</ul>
</div>
<div>
<h3>Admins</h3>
<ul>
{chatters.admins.map(chatter => {
return <li key={chatter.key}>{chatter}</li>;
})}
</ul>
</div>
<div>
<h3>Global Mods</h3>
<ul>
{chatters.global_mods.map(chatter => {
return <li key={chatter.key}>{chatter}</li>;
})}
</ul>
</div>
<div>
<h3>Plebs</h3>
<ul>
{chatters.viewers.map(chatter => {
return <li key={chatter.key}>{chatter}</li>;
})}
</ul>
</div>
</div>
);
}
}

Answer

Just use the twitch username. React doesn't need some fancy key, it just needs to be a unique value that stays the same for that individual rendered element.

example:

chatters.viewers.map(chatterName => {
  return <li key={chatterName}>{chatterName}</li>;
})
Comments