Reputation: 5750
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?
Upvotes: 1
Views: 169
Reputation: 104369
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.
Upvotes: 2