MateoIO
MateoIO

Reputation: 411

ReactJS key not showing

Attempting to generate a table using ReactJS and within this table I want to have a unique key to identify each row (as recommended by ReactJS). The following code runs and generates the table I desire except with the following error:

Warning: 'Each child in an array or iterator should have a unique "key" prop' 

Looking at my generated HTML the 'key' field indeed does not exist. I've also tried key={index} but it doesn't work either

export class Tablecontent extends Component{

  constructor(props){
    super(props);
    this.state={
      fileinfo:'null'
    }
  }
  render(){
    //const fileinfo = this.props.rows;
    const fileinfo = ['myFile1.doc','myFile2.doc'];
    var row='';
    console.log("FILEINFO:"+fileinfo);
    if(fileinfo=='null')
    {
       row ='';
    }
    else {

     row = fileinfo.map((data,index) =>
    <tr>
      <td key="filename_{index}">{data}</td>
      <td key="date_{index}">2/12/2017</td>
      <td key="size_{index}">2.1 MB</td>
    </tr>
    );
  }
    return(
      <div>
        <table>
        <tbody>
          <tr>
            <th>Name</th>
            <th>Date Created</th>
            <th>Size</th>
          </tr>{row}</tbody>
    </table>
      </div>
    );

  }
}

Resulting HTML:

<table>
    <tbody>
    <tr><th>Name</th><th>Date Created</th><th>Size</th></tr>
     <tr><td>myFile1.doc</td><td>2/12/2017</td><td>2.1 MB</td></tr>
    <tr><td>myFile2.doc</td><td>2/12/2017</td><td>2.1 MB</td>
    </tr>
    </tbody>
</table>

Upvotes: 4

Views: 10339

Answers (1)

brub
brub

Reputation: 1153

It wants to see the key on the outer element returned in the map function as below. The key is for React's internal use and won't display in the html.

 row = fileinfo.map((data,index) =>
    <tr key={index}>
      <td key="filename_{index}">{data}</td>
      <td key="date_{index}">2/12/2017</td>
      <td key="size_{index}">2.1 MB</td>
    </tr>
    );

Upvotes: 15

Related Questions