I am trying to access tags on an article using react. At the backend, I implemented tagging functionality using Django-taggit and the tags are returned as an array of strings.
Then, this is how I have implemented looping through the tags in react
<ul className="tags" >
{!article.tags ? "" : article.tags.map(tag => (
<Link to="/view-articles">
<li className="d-inline tag-name"
key={tag}
value={tag}>
{tag}
</li>
</Link>
))}
</ul>
The problem is, react gives the error ‘Missing "key" prop for element in iterator’
How do I go about resolving this? It seems I need a unique identifier for each tag for this to work
Add a key prop to Link.You don't need key on the li element.You need it at the topmost element of the JSX that your are repeating in map.Keep in mind that the key prop should be a unique constant.If your tags are unique,then just use the tag value or i prefer to do something like this. Concatenating the tag and index so that even if the tag repeats,the resulting string will be unique.
article.tags.map((tag,index) => (
<Link key = {`${tag}-index`} to="/view-articles">
<li className="d-inline tag-name"
value={tag}>
{tag}
</li>
</Link>
As a sidenote, {${tag}-index
} just means {tag + '' + index}.I prefer ES6 template literals to string concatenation.