Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display comma separated elements of array in React

Tags:

reactjs

jsx

 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?

like image 447
sugandh goyal Avatar asked Apr 09 '17 17:04

sugandh goyal


2 Answers

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>
                 )
      })
     }
like image 156
Shubham Khatri Avatar answered Sep 30 '22 16:09

Shubham Khatri


You can use if expression or ternary operator:

<span>
    {
      testArray.length ? testArray.map((itemTestArray) =>
      (<span> {itemTestArray} </span>)) : '-'
    }
</span>
like image 45
Vasyl Gutnyk Avatar answered Sep 30 '22 16:09

Vasyl Gutnyk