Reputation: 348
In my React app (really basic at the moment) I have an array inside another array and I want to loop over all this content. So far my code is:
{recipes.map((recipe) => (
<Recipe
key={recipe.uid}
title={recipe.data.title?.[0]?.text || null}
description={recipe.data.intro?.[0]?.text || null}
image={recipe.data.featured_image.url || null}
imageAlt={recipe.data.featured_image.alt || null}
aventuraTitle={recipe.data.tipo_aventura[0].tipo_titulo?.[0]?.text || null}
/>
))}
In this code I want aventuraTitle show all the tipo_titulo?.[0]?.text that exist.
As you can imagine this show only the first title.
I don't know what is the best way to loop over this array in React. Could you please advise me? If you need any extra information, please let me know.
Upvotes: 0
Views: 74
Reputation: 14436
You can do another map to just get the text strings and pass them down as another prop:
{recipes.map((recipe) => (
<Recipe
key={recipe.uid}
title={recipe.data.title?.[0]?.text || null}
description={recipe.data.intro?.[0]?.text || null}
image={recipe.data.featured_image.url || null}
imageAlt={recipe.data.featured_image.alt || null}
aventuraTitle={recipe.data.tipo_aventura[0].tipo_titulo?.map(x => x?.text || null)}
/>
))}
You can also pull this up to be a variable too to reduce the code a bit
{recipes.map((recipe) => {
const tipo_titulo = recipe.data.tipo_aventura[0].tipo_titulo?.map(x => x?.text || null);
return (
<Recipe
key={recipe.uid}
title={recipe.data.title?.[0]?.text || null}
description={recipe.data.intro?.[0]?.text || null}
image={recipe.data.featured_image.url || null}
imageAlt={recipe.data.featured_image.alt || null}
aventuraTitle={tipo_titulo }
/>
)}
)}
Upvotes: 0
Reputation: 2737
Inside <Recipe/>
component you need to map
tipo_titulo array to view all the texts you need to view and pass aventuraTitle={recipe.data.tipo_aventura[0].tipo_titulo || null}
to your <Receipe/>
component as a prop.
Upvotes: 0
Reputation: 1320
Try this:
{recipes.map((recipe) => (
<Recipe
key={recipe.uid}
title={recipe.data.title?.[0]?.text || null}
description={recipe.data.intro?.[0]?.text || null}
image={recipe.data.featured_image.url || null}
imageAlt={recipe.data.featured_image.alt || null}
aventuraTitles={recipe.data.tipo_aventura}
/>
))}
Then in the Recipe
component receive aventuraTitles
as a prop which will be having an array.
You can use map
on that the same way you did with the Recipe
component.
Upvotes: 1