class App extends Component {
constructor(props){
super(props);
this.state={ recipes :[] }
this.addRecipe=this.addRecipe.bind(this);
}
addRecipe (recipe) {
console.log({...recipe})
this.setState({
recipes: [...this.state.recipes, recipe]
});
}
componentWillMount(){
this.setState({
recipes : require('./sample-recipes')
});
}
render() {
return (
<div className="App">
<h2>Welcome to the Recipe Book</h2>
<dl>
{this.state.recipes.map(recipe => {
return ( <div key={recipe.name}>
<dt>{recipe.name}</dt>
<dd>{recipe.ingredient}</dd>
<hr></hr>
</div>
)
})
}
</dl>
<button className="addButton" onClick={() =>
{this.setState({ display: !this.state.display })}}>
Add Recipe
</button>
<AddRecipe addRecipe={this.addRecipe}
display={this.state.display} />
</div>
);
}
}
My sample-recipe.js file is as follows
module.exports = [
{
name : 'chicken',
ingredient : ['spinach','chillies']
}];
Hi, I am new to React.I am making this recipe book project. I want to display ingredients separated by space or comma. Now it is displaying as "spinachchillies". And is it a correct way of making ingredient an array?
Since ingredient is an array of strings
you can join
it to create a string and display the result
{this.state.recipes.map(recipe => {
return ( <div key={recipe.name}>
<dt>{recipe.name}</dt>
<dd>{recipe.ingredient.join(",")}</dd>
<hr></hr>
</div>
)
})
}
You can use if expression or ternary operator:
<span>
{
testArray.length ? testArray.map((itemTestArray) =>
(<span> {itemTestArray} </span>)) : '-'
}
</span>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With