Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading