skip to Main Content

I have a component that I am trying with various props that I want to pass. One of which being an array (tags):

<RandomItem
    propOne="alphabet"
    propTwo="numbers"
    propThree="months"
    propFour="days"
    propFive="weeks"
    tags={["alpha", "bravo", "charlie"]}
/>

the structure for the RandomItem component is as such (I did not include other props beside tags):

export function RandomItem ({propOne, propTwo, propThree, propFour, propFive, tags}) {

    const tagSet = tags.map(tagItem => {
        return (
            <Tag tagName={tagItem}/>
        )
    })

    return (
        <div>
           {tagSet}
        </div>
    )
}

I want to pass elements in the tags array to RandomItem but it keeps throwing an error as seen below. I have looked through the docs to work on different variations of the code above but still experience issues.

error

Below is the structure of Tag with a prop called tagName which is defined as such:

export function Tag ({tagName}) {
    return (
        <li className="randomTailwind">
            <div className="randomTailwind">
                {tagName}
            </div>
        </li>
    )
}

Ultimately, RandomItem is an element in another component.

3

Answers


  1. Created a simple codesandbox code here . Check it out. It works fine, without any error. Let me know if there is anything else I can do for you.

    In the RandomItem when iterate over tagSet, provide a unique key for each item (in my example, I just provided name as key)

    const tagSet = tags.map((tagItem) => {
       return <Tag key={tagItem} tagName={tagItem} />;
    });
    
    Login or Signup to reply.
  2. You can map it directly to return like this:

    import React from "react";
    import { Tag } from "./Tag";
    
    export function RandomItem ({propOne, propTwo, propThree, propFour, propFive, tags}) {
    
        return (
            <>
            {
                tags.length > 0 ?
                tags.map((tagItem, i) => {
                    return <Tag tagName={tagItem} key={i}/>
                }) : <li>No data available</li>
            }
            </>
        )
    }
    
    
    Login or Signup to reply.
  3. tags might be undefined.
    Let’s suppose you don’t pass the tagSet property coz you forgot so it’s undefined then you have to add a check for this case even if you don’t forget.

    
        const tagSet = tags && 
               tags.map(tagItem => <Tag key={tagItem} tagName={tagItem}/>)
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search