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 it
Here is the working version.
class App extends React.Component {
state = {
items: [ "Pumpkin Pie", "Spaghetti", "Onion Pie" ],
ingredients: [
[ "Pumpkin Puree", "Sweetened Condensed Milk", "Eggs", "Pumpkin Pie Spice", "Pie Crust" ],
[ "Noodles", "Tomatoe", "Sauce", "Meatballs" ],
[ "Onion", "Pie Crust" ],
],
}
render() {
return (
);
}
}
const Item = props => (
{props.items.map( ( item, index ) => (
{item}
{
props.ingredients[ index ].map( ingredient =>
- {ingredient}
)
}
) )}
);
ReactDOM.render( , document.getElementById("root"));
But if I were you I would change my state shape. Something like that:
class App extends React.Component {
state = {
items: [
{
name: "Pumpkin Pie",
ingredients: [
"Pumpkin Puree",
"Sweetened Condensed Milk",
"Eggs",
"Pumpkin Pie Spice",
"Pie Crust"
]
},
{
name: "Spaghetti",
ingredients: ["Noodles", "Tomatoe", "Sauce", "Meatballs"]
},
{
name: "Onion Pie",
ingredients: ["Onion", "Pie Crust"]
}
]
};
removeItem = item => {
const newItems = this.state.items.filter(el => el.name !== item.name);
this.setState({ items: newItems });
};
editItem = item => alert(`${item.name} will be edited`);
renderItems = () =>
this.state.items.map(item => (
));
render() {
return {this.renderItems()};
}
}
const Item = props => {
const { item, removeItem, editItem } = props;
const handleRemove = () => removeItem(item);
const handleEdit = () => editItem(item);
return (
{item.name}
{item.ingredients.map(ingredient => (
- {ingredient}
))}
);
};
ReactDOM.render( , document.getElementById("root"));
Changes
name and ingredients property. Maybe in the future, it may have a unique id? Objects are flexible.Item component, we are mapping the items in the parent component and pass just one item to the Item 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.