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粉5127298622023-07-20 09:52:35
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]