Jan
Jan

Reputation: 16094

Gatsby / React map is not a function (with example sandbox)

I am using a Gatsby / React page, and try to render a dynamic navigation. I am pretty new to React and wanna figure out why my Array isn't able to be iterated with .map.

It seems quite obvious but....

https://codesandbox.io/s/keen-platform-gy97p?file=/src/components/layout.js:891-923

layout.js

    const Layout = ({ children }) => {
      const navItems = [
        { title: "Hero", url: "#sec1", classes: "act-link", subnav: [] },
        { title: "About", url: "#sec2", classes: "", subnav: [] },
        { title: "Resume", url: "#sec3", classes: "", subnav: [] },
        { title: "Projects", url: "#sec5", classes: "", subnav: [] },
        { title: "Clients", url: "#sec6", classes: "", subnav: [] }
      ]
    
     return (
        <>
       
            <h1>Navigation goes here</h1>
            <nav>
              <Navigation {...navItems} />
            </nav>
            <main>{children}</main>
        </>
      )
    }

navigation.js

    import NavigationItem from "./navigation-item"
    
    const Navigation = navItems => {
      console.log(navItems)
      return (
        <nav>
          Here should appear the NavItems:
          {navItems.map(item => (
            <NavigationItem {...item} />
          ))}
        </nav>
      )
    }

export default Navigation

navigation-item.js

    import React from "react"
    const NavigationItem = (item, index) => {
      return (
        <li key={index}>
          <a className="scroll-link" href={item.link}>
            {item.title}
          </a>
        </li>
      )
    }
    
    export default NavigationItem

Any suggestions would be appreciated, thank you!

Upvotes: 1

Views: 588

Answers (1)

Evgeny Klimenchenko
Evgeny Klimenchenko

Reputation: 1194

navItems in your Navigation component is an object and not an Array and objects don't have .map method. Here is the potential fix:

layout.js

const Layout = ({ children }) => {
  const navItems = [
    { title: "Hero", url: "#sec1", classes: "act-link", subnav: [] },
    { title: "About", url: "#sec2", classes: "", subnav: [] },
    { title: "Resume", url: "#sec3", classes: "", subnav: [] },
    { title: "Projects", url: "#sec5", classes: "", subnav: [] },
    { title: "Clients", url: "#sec6", classes: "", subnav: [] }
  ]

 return (
    <>
   
        <h1>Navigation goes here</h1>
        <nav>
          <Navigation navItems={navItems} />
        </nav>
        <main>{children}</main>
    </>
  )
}

navigation.js

import NavigationItem from "./navigation-item"

const Navigation = ({ navItems }) => {
  console.log(navItems)
  return (
    <nav>
      Here should appear the NavItems:
      {navItems.map(item => (
        <NavigationItem {...item} />
      ))}
    </nav>
  )
    }

export default Navigation

Upvotes: 2

Related Questions