I am trying to create a function that takes an array of words such as:
const words = ['hello', 'my', 'name']
and returns them in the form:
<>
<span>hello</span> // <span>my</span> // <span>name</span>
</>
This is the react component I created to do this:
function StyleWords({words, ...props}){
return(
words.map((word, index, words) => {
if(index != words.length-1){
return <><span key={word} className='highlight'>{word}</span> // </>
}
else{
return <span key={word} className='highlight'>{word}</span>
}
})
)
}
and then call it like so:
<div><StyledWords words={['hello', 'my', 'name']} /></div>
Now this does work but I get the warning about keys. So my thinking is that either I have done this inappropriately or that I have missed something out with the keys. Any help?
CodePudding user response:
You need to provide the key
to the component which is the root of the item in the list.
function StyleWords({words, ...props}){
return(
words.map((word, index, words) => {
if(index != words.length-1){
return <React.Fragment key={word}>
<span className='highlight'>{word}</span> //
</React.Fragment>
}
else{
return <span key={word} className='highlight'>{word}</span>
}
})
)
}
As Lokesh suggested, you should use a unique value as key
for the items instead of using word
if it is not guaranteed that it will be unique.
CodePudding user response:
Some other optimizations:
function StyleWords({words, ...props}){
return(
words.map((word) => {
return <span key={word} className='highlight'>{word}</span>)
}
)
}
- Top level Element needs the key attribute.
- No need for fragment if you just use one element.
words.map((word, index, words)
was unnececcary.