Home > Software engineering >  How to fix unique "key" prop in ReactJS table?
How to fix unique "key" prop in ReactJS table?

Time:03-08

Code:

<tr 
  key={playdata.idx} 
  tabIndex={playdata.idx} 
  className="border_bottom" 
  onKeyDown={(e) => handleKeyDown(e, playdata.idx)} 
  onl oad={() => active(playdata.idx)}                             
  ref={playdata.idx === 0 ? myRef : null} 
  onm ouseDown={(e) => ClickHighlight(e, playdata.idx)}
  style={isHighlighted ? { backgroundColor: '#254368' } : {}}
>
  <td style={{ color: "white", width: "440px" }}>
    {playdata.ClipName}
  </td>
  <td style={{ color: "white", width: "250px" }}>    
    <select 
      id="lang" 
      value={playdata.ChannelName} 
      autoFocus
      className="btn_primary" 
      onChange={e => setPlayer(e.target.value, playdata.idx)} 
    >                                           
      {
        Channelname.map((val) => {                                              
          return (
            <>
              {
                removeRedundant([...val, playdata.ChannelName]).map((val1,index1) => {
                  //console.log(val1,index1);
                  return <option value={val1} key={index1}>{val1}{index1}</option>;
                })
              }
            </>
          )
        })
      }
    </select>

I get this warning: Each child in a list should have a unique "key" prop. for the option tag in the select tag. How can I add a key to remove the warning?

CodePudding user response:

As per React docs -

Note that the <></> syntax does not accept attributes, including keys.

If you need a keyed fragment, you can use directly. A use case for this is mapping a collection to an array of fragments

{props.items.map(item => (
    // Without the `key`, React will fire a key warning
    <Fragment key={item.id}>
      <dt>{item.term}</dt>
      <dd>{item.description}</dd>
    </Fragment>
  ))}

You can read more here - https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html#keyed-fragments

CodePudding user response:

The warning is from the fragment <> that is inside the Channalname.map function. You need to add the key prop as well, like this:

Channelname.map((val, id) => { return <Fragment key={id}...

Note that I'm not writing fragment tag as <> but as <Fragment>. And you would have to import it from react.

  • Related