Search code examples
javascriptreactjsreact-key-index

Reactjs Encountered two children with the same key, `NaN`. Keys should be unique


I have tried different things to eliminate Encountered two children with the same key, NaN. Keys should be unique and this is partial log:

in DynamicFields (at TableHeader.js)
in th (at TableHeader.js)
in TableHeader

Which is basically this bit of the TableHeader.js component, the full code is pasted lower down on this page:

return (
        <th key={cleanTitle + - + index}
            ref={(th) => th = th}
            style={{width:width}}
            data-col={cleanTitle}
         >

         <span className="header-cell" key={index*11}>{title} </span>
         <DynamicFields key={header.index+title} parentIndex={(index + 3) + title} />
       </th>
      );

I have read through this discussion about keys and reactjs , followed it but still the error did not stop.

Here are the 3 component involved in rendering the datatable:

MyDatatable.js
import React from "react";
import TableHeader from "./TableHeader";

const MyDatatable = (props) => {
  columnHeaders =  [
        {title: "Id" , accessor: 'id' , index: 0},
        {title: "Name" , accessor: 'name', width: "300px", index: 2}
        ]
        
   rowData = [
      {id: 1, name: 'a', age: 29, qualification: 'B.com', rating: 3, profile: 'ps'},
      {id: 2, name: 'b', age: 35, qualification: 'B.Sc', rating: 5, profile: 'h'}
   ]
        
  const [headers, setHeaders] = React.useState(columnHeaders);

  const [data, setData] = React.useState(rowData)
  
  const  renderContent = () => {
    let contentView = data.map((row, rowIdx) => {
    let id = row[keyField];
    let tds = headers.map((header, index) => {
    let content = row[header.accessor];

    return (
      <td key={index} data-id={id} data-row={rowIdx}>
        {content}
      </td>
     );
   });
        
   return (
     <tr key={rowIdx}>
       {tds}
     </tr>
    );
            //
  }); //closes contentView variable

 return contentView;
}

const renderTable = () => {
  let title = props.title || "DataTable";
  let contentView = renderContent();
          
  return (
    <table className="data-inner-table table-responsive">
      <caption className="data-table-caption">
        {title}
      </caption>
      <thead>
        <tr>
          <TableHeader headers={headers} />
        </tr>
      </thead>

      <tbody>
        {contentView}
      </tbody>
    </table>
  )}  

  return (
    <React.Fragment>
      <div className={props.className}>
        {renderTable() }
      </div>
    </React.Fragment>
  )
}
TableHeader.js
import React from "react";
import DynamicFields from "../DynamicFields";

const TableHeader = (props) => {
  let FieldTypes = ["text", "dropdown"];
  
  const renderTableHeader = () => {

    headers.sort((a, b) => {
      if (a.index > b.index) return 1;
      return -1
    });

    const headerView = headers.map((header, index) => {
      let title = header.title;
      let cleanTitle = header.accessor;
      let width = header.width;

      return (
        <th key={cleanTitle + - + index}
            ref={(th) => th = th}
            style={{width:width}}
            data-col={cleanTitle}
         >

         <span className="header-cell" key={index*11}>{title} </span>
         <DynamicFields key={header.index+title} parentIndex={(index + 3) + title} />
       </th>
      );

  } );

    return headerView;
  }

  return(
    <React.Fragment>
     {renderTableHeader()}
    </React.Fragment>
  )
}
DynamicFields.js
import React, { useState, useEffect, useRef } from "react"

const DynamicFields = (props) => {
  const  optionsHash =  ['Checkbox', 'Dropdown', 'boolean', 'Single line text'];

  const [showDynamicField, setShowDynamicField ] = useState(false);

  // const dropdownRef = useRef();
  
  
   const handleShowDynamicField = (event) => {
     setShowDynamicField(!showDynamicField);
   };

  return (
    <React.Fragment>
      <i className="bi bi-chevron-compact-down" onClick={handleShowDynamicField}></i>

     {showDynamicField &&
       optionsHash.map( (val, idx) => {
                return(
                 <li key={val-idx}  value={val} className="dropdown-item"> {val} </li>
                )
       })
     }
    </React.Fragment>
  )
}

Solution

  • - is the subtraction operator, which will cause problems with key={val-idx} (string - number => NaN).
    Presumably you want to use - as a separator character, so you'd use it as a string: key={val + '-' + idx} or key={`${val}-${idx}`}

    In this case, since optionsHash has all unique strings, you could get away with just using key={val}.

    The reason key={cleanTitle + - + index} works is because it evaluates to cleanTitle + (- +index), adding a negative number to a string which is allowed (but confusing).