+ 2

Ternary operators

I need a ternary operator here but not sure of the structure. Or is best practice is to add inside of map? I'm confused of how this works {this.state.recipes.map((recipe, id) =>{ return ( <div> Hi </div> )}

1st Mar 2019, 3:06 AM
A B
A B - avatar
5 Answers
+ 3
What is the condition you wish to set from your ternary operator?
1st Mar 2019, 4:17 AM
CalviŐ˛
CalviŐ˛ - avatar
+ 1
Normally we run map first then filter it using ternary operator in its callback.
1st Mar 2019, 5:13 AM
CalviŐ˛
CalviŐ˛ - avatar
0
I want the ternary statement to check if something exists then if it does to run the map
1st Mar 2019, 4:18 AM
A B
A B - avatar
0
Here an example I could show according to your recipes app roughly. class App extends React.Component { constructor(props) { super(props); this.state = { recipes: [ { recipe: "Dish Chinese 1", type: "Chinese" }, { recipe: "Dish Usa 1", type: "American" }, { recipe: "Dish Chinese 2", type: "Chinese" }, { recipe: "Dish Usa 2", type: "American" }, ] } } render() { return ( <div> <h3>Chinese Recipes</h3> <ul> { this.state.recipes.map((recipe, id) => recipe.type=='Chinese' ? <li>Recipe: {recipe.recipe} </li> : null ) } </ul> </div> ); } }
1st Mar 2019, 5:55 AM
CalviŐ˛
CalviŐ˛ - avatar