tsahib
tsahib

Reputation: 45

Mapping array inside array with React

I have a database in MongoDB and one of the props in the document contains an array. I'm trying to map the collection in the client-side using React using this code:

<div>
    <h2>Recipes</h2>
    <ul>
        {this.state.recipes.map(recipe =>
            <li key={recipe._id}>
                {recipe.title}<br/>{recipe.category}<br/> 
                {recipe.ingredients}<br/>{recipe.preparation}
            </li>
        )}
    </ul>
</div>

ingredients prop is an array and I want to map it too. How can I do it? Any help would be great, thanks!

Upvotes: 0

Views: 169

Answers (4)

szczocik
szczocik

Reputation: 1333

Just map it the same way you do with recipes

<div>
    <h2>Recipes</h2>
    <ul>
        {this.state.recipes.map(recipe =>
            <li key={recipe._id}>
                {recipe.title}<br/>
                {recipe.category}<br/> 
                {recipe.ingredients.map(ingredient => (
                   <span>{ingredient}</span>
                ))}
                <br/>{recipe.preparation}
            </li>
        )}
    </ul>
</div>

Upvotes: 4

Surya Kavutarapu
Surya Kavutarapu

Reputation: 136

<div>
    <h2>Recipes</h2>
    <ul>
        {this.state.recipes.map(recipe =>
            <li key={recipe._id}>
                {recipe.title}<br/>{recipe.category}<br/> 
                 {  recipe.ingredients.map(ingredient => 
                    <span>{ingredient}</span>
                  )}                 
                <br/>{recipe.preparation}
            </li>
        )}
    </ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Upvotes: 2

thelittlemaster
thelittlemaster

Reputation: 403

just map it again

<div>
    <h2>Recipes</h2>
    <ul>
        {this.state.recipes.map(recipe =>
            <li key={recipe._id}>
                {recipe.title}<br/>
                {recipe.category}<br/> 
                {recipe.ingredients.map(k =>(
                   <span key={k._id}>{k}<span>
                 )<br/>
                {recipe.preparation}
            </li>
        )}
    </ul>
</div>

Upvotes: 3

norbitrial
norbitrial

Reputation: 15166

You can also use .map() there by calling recipe.ingredients.map() as the following:

{this.state.recipes.map(recipe =>
    <li key={recipe._id}>
        {recipe.title}<br/>{recipe.category}<br/> 
        {
           recipe.ingredients.map((elem, index) => 
             <div key={index}>
                {elem /* or maybe elem['your-property-name'] if it's not a string */}
             </div>
           )
        }<br/>{recipe.preparation}
    </li>
)}

Also don't forget to add key={index} there to avoid the warning based on Lists and Keys.

Upvotes: 1

Related Questions