0

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
            })}
skksks
  • 53
  • 1
  • 2
  • 8
  • If you add key-prop to those spans, it might work., so like – Swiffy Nov 18 '21 at 09:38
  • This doesn't look like a very efficient way of approaching the problem. All your spans are identical with the exception of the argument you're passing into the function. – Andy Nov 18 '21 at 09:39
  • https://robinpokorny.com/blog/index-as-a-key-is-an-anti-pattern/ – Andy Nov 18 '21 at 10:17

2 Answers2

2

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>
 })}
kiranvj
  • 32,342
  • 7
  • 71
  • 76
1

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>
})}
Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60
  • 1
    You shouldn't be using index as a key, it can cause problems and will throw a console error. You should be using some kind of unique ID or something which will not repeated in the map. – Marts2390 Nov 18 '21 at 09:45
  • But if the list is not going to be updated, reordered and be static as it is and you do not have item id then using key as index is ok. – Piyush Nov 18 '21 at 10:30