Nyi Nyi Hmue Aung
Nyi Nyi Hmue Aung

Reputation: 736

How to pass key to react component

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

Upvotes: 3

Views: 4504

Answers (3)

Hozeis
Hozeis

Reputation: 1742

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.

Upvotes: 3

windmaomao
windmaomao

Reputation: 7680

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={...} />

Upvotes: 1

Sobhan Jahanmard
Sobhan Jahanmard

Reputation: 890

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>

Upvotes: 0

Related Questions