How to pass key to react component

Viewed 1633

I know this is a very basic question and even beginners can do this. But somehow I am getting this error:

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

Check the render method of FilterProducts.

Here is my code

const filterList = filterBy.map((f, i) => {
    const key = Object.keys(f);
    return (
      <div key={i} className="filter">
        <h4 className="filter__header">{key}</h4>
        {f[key].map((val) => {
          return (
            <CheckBoxInput
              changeVal={(e) => changeValHandler(e, key)}
              value={val.toLowerCase()}
              label={val}
            />
          );
        })}
      </div>
    );
  });

I am rendering 2 lists, I provided the key to the first list and as for the second one I don't know how to pass a key. It's a component and if I pass key to that component, it complains that key can't be passed as a prop. Give me some help here please

3 Answers

I believe your code is incorrect on this line:

{f[key].map((val) => {

you already retrieved the keys for f here:

 const key = Object.keys(f);

So what your code should actually look like is:

const filterList = filterBy.map((f, i) => {
    const keys = Object.keys(f);
    return (
      <div key={i} className="filter">
        <h4 className="filter__header">{keys}</h4>
        {keys.map((val) => {
          return (
            <CheckBoxInput
              key={val} // then just use the f property key as the key (if unique)
              changeVal={(e) => changeValHandler(e, key)}
              value={val.toLowerCase()}
              label={val}
            />
          );
        })}
      </div>
    );
  });

Then just use the f property key as the key (if unique) for the second loop of components.


Also not sure what you would like to display on this line

<h4 className="filter__header">{keys}</h4>

But as the code is written so far, this would display an array of keys.

You actually did it right. But there're two loops in your code, each loop needs to have the looped element tagged with a key prop. As long as the key is unique for that loop, that's fine.

  <CheckBoxInput key={...} />

Pass it like this:

 {f[key].map((val,i) => {
          return (
         <div key={i}>
            <CheckBoxInput
              changeVal={(e) => changeValHandler(e, key)}
              value={val.toLowerCase()}
              label={val}
            />
         </div>
Related