Search code examples
javascriptreactjsnext.jsforeach

Generating multiple NextJS Components


I'm currently learning NextJS and I want to create a website that shows multiple projects that I've created with it.

I have a "Tag" component which is a sort of button template with custom text that I want to pass through props :

export default function Tag({val}) {
    return(
        <>
            <p>{val}</p>
        </>
    )
}

Then, in my Block component, I want to generate as many Tag components as there are in an array passed through props :

import Tag from "./Tag"

export default function Block({tags, name}) {
    return(
        <>
            <section>
                <div></div>
                <h2>{name}</h2>
                <div>
                    {tags.forEach(tag => <Tag val={tag} />)}
                </div>
            </section>
        </>
    )
}

This Block component is then called in the main page :

import Block from './components/Block'

export default function Home() {
  return (
    <>
      <Block tags={["Webflow", "UI Design"]} name="Projet 1" />
    </>
  )
}

The problem is : no tags show up.

I think the problem is linked to the forEach method because when I try to generate a single tag without the forEach method, it works.

Can you figure out the problem ?

Thanks, Lucas.


Solution

  • You are using forEach and nothing returns in this function. You can use array.map function.

    {tags.map(tag => <Tag val={tag} />)}
    

    const tags = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    const result = tags.forEach(tag => tag)
    console.log(result) //undefined
    
    const mapResult = tags.map(tag => tag)
    console.log(mapResult) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]