Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Concatenate string for key

Tags:

reactjs

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'))
like image 461
user6213384 Avatar asked Nov 04 '16 14:11

user6213384


1 Answers

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.

like image 192
Rami Enbashi Avatar answered Nov 13 '22 20:11

Rami Enbashi