Reputation: 91
I get a message as following: 'Warning: Each child in a list should have a unique "key" prop'.
Any way to automatically add keys to the elements inside 'content'?
const ArticlesArray = [
{
id: 2,
title: `title`,
subtitle: `subtitle`,
linkUrl: `articles/2`,
content: [
<h5>text</h5>,
<p>
more text
</p>,
<p>
and some more text
</p>
]
},
];
return (
<div className="article-container">
<h3> {filteredArticle[0].title} </h3>
<h4> {filteredArticle[0].subtitle} </h4>
<hr />
<div>
{ filteredArticle[0].content.map(p =>
p)
}
</div>
</div>
);
EDIT: Solved
<div>
{filteredArticle[0].content.map((p, idx) => (
<div key={idx}>{p}</div>
))}
</div>
Upvotes: 0
Views: 1314
Reputation: 143
you can try with adding unique key to the your Components
$return(
<CustomComponents
key={item.id} //unique key id
/>
);
or
$render() {
return (
<ol>
{this.props.results.map((result, i) => (
<li key={i}>{result.data}</li>
))}
</ol>
);
}
Upvotes: 2
Reputation: 12874
Your question is not really completed. If I'm to guess, you are trying to render the component based on ArticlesArray
, via the map
method?
If that's the case, you can refer to below
render () {
return ArticlesArray.map(ele => (
<MyCustomsComponent key={ele.id} ... /> // <<<<==== HERE
))
}
The idea is that, for each and every component that you're trying to render, gives it a prop key
and assign a unique value which allows React to identify the element in that array
Upvotes: 0
Reputation: 1449
I suggest rethinking your use case as it might be an anti pattern. To answer your quesiton: You can loop through your contents array and set a key for each entry quite easily, e.g
ArticlesArray[0].content = ArticlesArray[0].content.map((e, idx) => (e.key = idx, e));
The above code sets the key of each element in the content array to its index.
Upvotes: 0