Nothing Rendered from forEach

I am attempting to output an array into a Material-UI chip. I am getting the array from an Apollo GraphQL query. I can see the output of the array in a console.log() from the forEach() function, but I am not getting any HTML from the JSX. Below is what I am running:

{posts.tags.forEach((tag, i) => (
  <Chip key={i} label={tag} />

I tried to replace the component with just <p>{tag}</p> but there is still not HTML being rendered from this function. Like I said, if I put console.log(tag) in the forEach() I can see the console output, it is just not coming from HTML.

forEach is for side effects, you want map. You are creating an array of components from your post tags, forEach doesn’t do that (it’s the same as a for loop, it’s of extremely limited use in the context of React & JSX)

1 Like

You know I originally typed up that function with map but then stopped and said to myself that wouldn’t output. Does it just present the array of components as HTML?

React will flatten an array of elements into adjacent ones when it renders. Just return the array and React will Do The Right Thing. Keep in mind that each component does have to be contained within a single tag though (fragments notwithstanding, but don’t reach for those right away)

1 Like

Thank you both for your help. I feel a bit foolish cause I remember learning this now. Never hurts to get the experience though.