1

I am a little confused with the map function when using it in a React Component. I have a Recipes Component that gets passed the recipes data from the App Component.

APP COMPONENT

<Recipes recipes={recipes} />

RECIPES COMPONENT

export default class Recipes extends Component {
  // THIS FUNCTION IS RETURNING NOTHING
  renderRecipes() {
    return this.props.recipes.map((recipe) => {
      <h1>{recipe.name}</h1>
    });
  }
  render() {
    let recipe = this.props.recipes.map((recipe) => {
      return (
        <h1>{recipe.name}</h1>
      );
    });
    return(
      <div>
        // CALLING THE FUNCTION HERE DOES NOT WORK
        { this.renderRecipes() }
        // HOWEVER CALLING THE VARIABLE DOES WORK
        { recipe }
      </div>
    );
  }
}

Here is where I am confused. Creating a function which does the map function returns nothing, however moving the map function and assigning the output to the recipe variable inside render() works fine. Why does the map function in renderRecipes return nothing?

1
  • 2
    not returning in map of renderRecipes Commented May 22, 2017 at 4:42

1 Answer 1

2

Because you are not returning anything inside map body, use it like this:

renderRecipes() {
    return this.props.recipes.map((recipe, i) => {
        return <h1 key={i}> {recipe.name} </h1>
    });
}

or remove the {}:

renderRecipes() {
    return this.props.recipes.map((recipe, i) => <h1 key={i}> {recipe.name} </h1> );
}

When {} is required with map?

When you want to do some calculation or want to return different elements on the basis of some condition then use {} to create a scope to define some variables and to use if conditions but here you just want to return a single element so {} is not required here.

Note: You need to assign unique key to each element, here i used index but i will suggest you to use any unique property of recipe object.

Sign up to request clarification or add additional context in comments.

1 Comment

That did it! Will accept when I can. I am guessing I will need the {} if I want to return multiple lines of html? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.