skip to Main Content

I have values ​​in an array object called farms. In this case, we are using the farms.map function.
However, this warning occurred, and when I searched the documentation, it was telling me to write a unique value for key.

Warning: Each child in a list should have a unique "key" prop. in React native?

So I wrote v.placeId in the key in the TargetCon component, but the warning was not resolved. How do I fix it?

this is my code

    farms = [
    {
        placeId: 272,
        name: 'hamburger',
    },
    {
        placeId: 273,
        name: 'coffee',
    },
    ];

    const TargetFarm = () => {
    const {farms} = useSelector((state: RootState) => state.post);

    return (
        <SeCotainer platform={tablet}>
        {farms.map(v => {
            return (
            <>
                <TargetCon key={v.placeId.toString()}>
                <TargetTxt platform={tablet}>{v.name}</TargetTxt>
                </TargetCon>
            </>
            );
        })}
        </SeCotainer>
    );
    };

    export default TargetFarm;

3

Answers


  1. Add the key attribute in root element within the loop

    return (
            <React.Fragment  key={v.placeId.toString()}>
                <TargetCon>
                     <TargetTxt platform={tablet}>{v.name}</TargetTxt>
                </TargetCon>
            </React.Fragment>
    );
    
    Login or Signup to reply.
  2. In the above code, you have converted the value of the key into a string that wouldn’t work

    Refer to the below code I have made the changes:

        farms = [
    {
        placeId: 272,
        name: 'hamburger',
    },
    {
        placeId: 273,
        name: 'coffee',
    },
    ];
    
    const TargetFarm = () => {
    const {farms} = useSelector((state: RootState) => state.post);
    
    return (
        <SeCotainer platform={tablet}>
        {farms.map(v => {
            return (
            <>
                <React.Fragment key={`targetcon_${index}`}>
                  <TargetCon key={v.placeId.toString()}>
                    <TargetTxt platform={tablet}>{v.name}</TargetTxt>
                  </TargetCon>
                </React.Fragment>
            </>
            );
        })}
        </SeCotainer>
    );
    };
    
    export default TargetFarm;
    
    Login or Signup to reply.
  3. You can use index inside map() Function

      return (
          <SeCotainer platform={tablet}>
          {farms.map((v, index) => {
              return (
              <React.Fragment key={`targetcon_${index}`}>
                  <TargetCon key={v.placeId.toString()}>
                  <TargetTxt platform={tablet}>{v.name}</TargetTxt>
                  </TargetCon>
              </React.Fragment>
              );
          })}
          </SeCotainer>
      );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search