Custom function I made that returns <span> elements is getting "Warning: Each child in a list should have a unique 'key' prop"

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?

>Solution :

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.

Leave a Reply