Devologist
Devologist

Reputation: 55

react mapping over array of objects

My current state is an array of objects. I am mapping over them and I am getting exactly what I want. However, inside of my array of objects I am not receiving the ingredients that I want. I am receiving the console.log of that value but the value it self I am not displaying anything on the dom. Heres my code. I am trying to have my ingredients show up inside of the li that I am mapping but when I click on my panels I am receiving no value. However, my console.log below it shows a value. idk...

import React from 'react';
import Accordian from 'react-bootstrap/lib/Accordion';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar';
import Modal from 'react-bootstrap/lib/Modal';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import FormControl from 'react-bootstrap/lib/FormControl';

export default class App extends React.Component {
  constructor () {
    super();

    this.state = {recipes: [
      {recipeName: 'Pizza', ingredients: ['Dough', 'Cheese', 'Sauce']},
        {recipeName: 'Chicken', ingredients: ['Meat', 'Seasoning', 'other']},
          {recipeName: 'Other', ingredients: ['other1', 'other2', 'other3']}
    ]};
    console.log(this.state.recipes);
  }
  render() {
    const recipes = this.state.recipes.map((recipe, index) => {
      return (
          <Panel header={recipe.recipeName} eventKey={index} key={index}>
            <ol>
              {recipe.ingredients.map((ingredient) => {
                <li> {ingredient} </li>
                console.log(ingredient);
              })}
            </ol>

          </Panel>
      )
    });
    return (
      <div className="App container">
         <Accordian>
          {recipes}
         </Accordian>
      </div>
    )
  }
}

Upvotes: 1

Views: 2887

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104369

Because you are not returning anything from inner map body.

Write it like this:

{recipe.ingredients.map((ingredient) => {
    console.log(ingredient);
    return <li key={...}> {ingredient} </li>      //use return here
})}

Or you can simply write it like this:

{
   recipe.ingredients.map((ingredient) => <li key={...}> {ingredient} </li>)
}

As per MDN Doc:

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

Check MDN Doc for more details about Arrow Function.

Upvotes: 2

Related Questions