Troy Crowe
Troy Crowe

Reputation: 123

Can someone help me understand the child keys issue I am having

Problem with child keys error but only when I refresh the browser. I am using reactjs and nextjs.

index.js:1 Warning: Each child in a list should have a unique "key" prop.

let cnt = 1;
  const counter = () => {
    return cnt++;
  };

  let pCnt = 1;
  const pCounter = () => {
    return pCnt++;
  };

  const renderInvoiceData = invoice => {
    let invoiceData = Object.values(invoice);
    let invoiceKeys = Object.keys(invoice);

    return invoiceKeys.map((invKey, index) => {
      return (
        <div className="col-3" key={counter()}>
          {invKey}
          <br />
          {invoiceData[index]}
        </div>
      );
    });
  };

  return (
    <div id="invoices" className="home-page">
      {data.map((invoice, index) => (
        <div className="card text-left mb-3">
          <div className="card-header">
            <Link href="/invoicerecord">
              <a>{invoice.invoiceNumber}</a>
            </Link>
          </div>
          <div className="card-body" key={pCounter()}>
            <div className="row">{renderInvoiceData(invoice)}</div>
          </div>
        </div>
      ))}
    </div>
  );
};

I am definitely providing unique keys as expected. This issue only happens when I manually refresh the browser using the reload button and repost the url

Upvotes: 1

Views: 81

Answers (1)

John Ruddell
John Ruddell

Reputation: 25862

You aren't setting the key on your map (in the return of your render).

{ data.map( invoice => (
    <div key={invoice.id} className="card text-left mb-3">
    {/*  ^--------------^ */ }
      <div className="card-header">
        <Link href="/invoicerecord">
          <a>{invoice.invoiceNumber}</a>
        </Link>
      </div>
      <div className="card-body" key={pCounter()}>
        <div className="row">{renderInvoiceData(invoice)}</div>
      </div>
    </div>
  ));
}

You shouldn't be using a counter to track your keys, thats a really inefficient way to do that. Instead use related data to track the rendering. invoice.id assuming you have a unique id for your invoices would be a great example of a key to use in React :)

Upvotes: 2

Related Questions