skip to Main Content

I’m trying to loop through an array called "experiences". When I run the code below I get this error:
TypeError: Cannot read properties of undefined (reading ‘map’)

How do I fix this?

const ProjectCard = ({ experience }) => {
    return (
        <div>
            <div>
                <h2>{experience.title}</h2>
                <h3>{experience.organization}</h3>
            </div>
        </div>
    )
}

const Projects = () => {
    return (
        <Layout>
            <div>
                {experiences.map((experience, index) => (
                    <ProjectCard key={index} experience={experience}/>
                ))}
            </div>
        </Layout>
    )
}

I tried renaming some of the variables because I thought maybe I had accidentally overlapped some of them but that didn’t seem to work.

3

Answers


  1. try using Array.isArray(experience) to make sure experience is array

    {Array.isArray(experience) && experiences.map((experience, index) => (
    ))}

    Login or Signup to reply.
  2. experiences is undefined, and hence you get

     TypeError: Cannot read properties of undefined (reading 'map')
    

    Hence you can make sure experiences is not null or undefined…
    There are many ways to do it.

    1. (experiences || []).map – or

    2. (experiences ?? []).map

      This will use empty array if experiences is undefined or null

    Login or Signup to reply.
    1. Use Ternary Operator

    make sure the experiences variable is an array or initialize it to an empty array initially in useState Hook

    const ProjectCard = ({ experience }) => {
        return (
            <div>
                <div>
                    <h2>{experience.title}</h2>
                    <h3>{experience.organization}</h3>
                </div>
            </div>
        )
    }
    
    const Projects = () => {
        return (
            <Layout>
                <div>
                    {experiences ? experiences.map((experience, index) => (
                        <ProjectCard key={index} experience={experience}/>
                    )): null}
                </div>
            </Layout>
        )
    }
    

    or you can use Logical &&

    const ProjectCard = ({ experience }) => {
        return (
            <div>
                <div>
                    <h2>{experience.title}</h2>
                    <h3>{experience.organization}</h3>
                </div>
            </div>
        )
    }
    
    const Projects = () => {
        return (
            <Layout>
                <div>
                    {experiences && experiences.map((experience, index) => (
                        <ProjectCard key={index} experience={experience}/>
                    ))}
                </div>
            </Layout>
        )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search