"react" Each child in a list should have a unique "key" prop

81 Views Asked by At

An error seems to occur because the key value is not entered in the map function, but I do not know how to modify the code.

The array is structured like this:

    const tabContArr=[
        {
            tabTitle:(
                <span className={activeIndex===0 ? "is-active" : ""} onClick={()=>tabClickHandler(0)}>0</span>
            ),
         
        },
        {
            tabTitle:(
                <span className={activeIndex===1 ? "is-active" : ""} onClick={()=>tabClickHandler(1)}>1</span>
            ),
           
        },
        {
            tabTitle:(
                <span className={activeIndex===2 ? "is-active" : ""} onClick={()=>tabClickHandler(2)}>2</span>
            ),
          
        },
        {
            tabTitle:(
                <span className={activeIndex===3 ? "is-active" : ""} onClick={()=>tabClickHandler(3)}>3</span>
            ),
           
        }
    ];

An error occurs in the map function part.

   {tabContArr.map((section)=>{
                return section.tabTitle
            })}
2

There are 2 best solutions below

2
Radonirina Maminiaina On BEST ANSWER

What you have done is not the right way. If you have data, instead of passing the ReactElement into the array you should pass it into the map function like this:

{tabContArr.map((tab, index)=>{
      return <span 
         className={activeIndex === index ? "is-active" : ""} 
         onClick={()=>tabClickHandler(index)} 
         key={`tab-${index}`}>index</span>
})}
0
kiranvj On

Try with React Fragments with a key attribute as mentioned in React docs

{tabContArr.map((section, index)=>{
    return <React.Fragment key={`section-tab-${index}`}>{section.tabTitle}</React.Fragment>
 })}