8

I am creating a list of list and want to put a unique key for each element. When I use the React Dev Tool, the new key is "2016-10,-,football".

  • Why does it have commas in it?
  • What is the correct way to specify a key when I want "2016-10-football"?

React Dev Tool Console

import React from 'react'
import ReactDOM from 'react-dom'

const dates = ['2016-10', '2016-11', '2016-12'];
const sports = ['football', 'baseball', 'basketball'];

const Dates = ( { dates, sports } ) => {
  return (
    <ul>
      { dates.map( date => {
        return (
          <div key={date.toString()}  >
            <li>{date}</li>
            <Sports sports={sports} date={date}/>
          </div>
          )
        })
      }
    </ul>
    )
}

const Sports = ( { date, sports } ) => {
  return(
    <ul>
      { sports.map( sport => {
        // Results in: key="2016-10,-,football"
        // Expected: key="2016-10-football"
        return (<li key={[date, '-', sport]} >{sport}</li>)
      })}
    </ul>
    )
}

ReactDOM.render(<Dates dates={dates} sports={sports}/>, document.getElementById('main'))
isherwood
  • 58,414
  • 16
  • 114
  • 157
user6213384
  • 135
  • 1
  • 1
  • 9

4 Answers4

9

key expects a string so when you pass an array you are calling the Array's .toString() function. You will see the same result if you do console.log([date, '-', sport].toString())

Replace [date, '-', sport] with date + '-' + sport to fix it.

Rami Enbashi
  • 3,526
  • 1
  • 19
  • 21
0

It's showing with commas because toString will use commas to join the array.

This is what you have:

arr = ['2016-10', '-', 'football']
console.log(arr.toString); // "2016-10,-,football"

This is what you want:

arr = ['2016-10', '-', 'football']
console.log(arr.join()); // "2016-10-football"

So consider replacing the li to (notice the .join()):

return (<li key={[date, '-', sport].join()} >{sport}</li>)

edit: use join("") for expected result, you should pass a separator (in this case an empty string) to arguments of the method. For example, ['2016-10', '-', 'football'].join('~separator~') would return "2016-10~separator~-~separator~football"

dogisdev
  • 47
  • 1
  • 8
JorgeObregon
  • 3,020
  • 1
  • 12
  • 12
0

Added some examples for better understanding

key={'company_'+index} // key={date +'-'+sport}

<TableCell key={'company_'+index} align="right">
     {row.company?.name}
</TableCell>


return(
    <ul>
      { sports.map( sport => {
        // Results in: key="2016-10,-,football"
        // Expected: key="2016-10-football"
        return (<li key={date +'-'+sport} >{sport}</li>)
      })}
    </ul>
    )
Rupesh Terase
  • 440
  • 3
  • 14
0

I had no problem using a plus sign to concatenate two fields to make a unique key:

 {rows.map((Group) => (
      <li key={Group.user_id + Group.lgroup_id}>
      -- Display the parts of the Group object here.  --
      </li>
 ))}
Steve Stilson
  • 1,015
  • 7
  • 11