Home > other >  Mapping through Contentful nested array is not working
Mapping through Contentful nested array is not working

Time:04-23

I've successfully managed to bring the data back from Contentful but I can't seem to map further into the array. I'm not sure what I'm doing wrong as I'm getting the following error: field.fields.map is not a function

export default function Header({ links }) {
  console.log(links);
  return (
      <div className='header-links'>
        <ul className='flex text-white uppercase tracking-widest font-medium'>
          {links.map((link) => (
            <div key={link.title}>
              {link.links.map((field) => {
                <div>
                  {field.fields.map((singleLink) => (
                    <p>{singleLink.title}</p>
                  ))}
                </div>;
              })}
            </div>
          ))}
        </ul>
      </div>
  );
}

[
  {
    "title": "Header",
    "logo": {},
    "links": [
      {
        "fields": {
          "title": "Home",
          "slug": "/"
        }
      },
      {
        "fields": {
          "title": "Food",
          "slug": "/Food"
        }
      },
    ]
  }
]

CodePudding user response:

Change it in this way. When you are inside the field, they are already object so you can not map like array anymore

export default function Header({ links }) {
  console.log(links);
  return (
      <div className='header-links'>
        <ul className='flex text-white uppercase tracking-widest font-medium'>
          {links.map((link) => (
            <div key={link.title}>
              {link?.links?.map((field) => (
                <div>
                <p>{field?.fields?.title}</p>
                </div>
              )
            )}
            </div>
          ))}
        </ul>
      </div>
  );
}

  • Related