Generate multiple NextJS components
P粉513318114
P粉513318114 2023-07-19 18:17:07
0
1
511

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

I have a component called "Tag" which is a button template with custom text and I want to pass it via props:


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

Then, in my Block component, I want to generate a corresponding number of Tag components based on the number of elements in the 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>
        </>
    )
}

Then, this Block component is called on the home page:

import Block from './components/Block'

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

The problem is: no tags are displayed.

I think the problem is related to the forEach method because when I try to generate a single label without the forEach method it works fine.

What’s the problem?

P粉513318114
P粉513318114

reply all(1)
P粉512729862

You used the forEach method, but nothing was returned in this function. You can use the map method of the array.

{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]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!