I'm a React noob and making a ToDo list style Recipe List app. I have a functional component, Item.js, and I am using JSX and the map function to iterate through each recipe item and display them. I want each recipe item to appear on a new line, but when I use .map to iterate through them React puts the entire list of recipe items into one p tag instead of one p tag for each item.
How can I iterate through the recipe items and display them on separate lines? Even if I try to display them as an unordered list React wants to throw each item in one li tag.
Here is my code:
import React from 'react';
import Button from 'react-bootstrap/lib/Button';
const Item = (props) => (
<div>
<div className="Recipe-Item-Container" key={props.text}>
{props.items.map((item, index) =>
<div className="Recipe-Item" key={index}>
<h3>{item}</h3>
<p>{props.ingredients[index]}</p>
<div className="buttons-container">
<Button className="edit-button" onClick={() => props.edit(item, index)}>Edit</Button>
<Button className="delete-button" onClick={() => props.delete(item, index)}>Delete</Button>
</div>
</div>
)}
</div>
</div>
)
export default Item;
Also on the {props.items.map((item, index) =>
line if I add a curly brace after the => I get an error. I have a React/JSX linter installed and it isn't catching anything. What's the issue?
I know this is probably a noob error but JSX is throwing me for a loop here.
If you add curly braces after the fat arrow, you will have to explicitly return the
JSX
.Here is the working version.
But if I were you I would change my state shape. Something like that:
Changes
name
andingredients
property. Maybe in the future, it may have a uniqueid
? Objects are flexible.Item
component, we are mapping the items in the parent component and pass just one item to theItem
component.item
prop itself! You can see how we handle the remove functionality: with.filter
You can apply the same functionality to other functions..map
,.filter
,Object.assign
or spread syntax are all good tools. Just, avoid mutating your state directly.