6
 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?

1
  • i also want to learn react... what is the best source to cover all important topics... Commented Dec 21, 2017 at 9:30

6 Answers 6

18

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>
                 )
      })
     }
Sign up to request clarification or add additional context in comments.

1 Comment

This also shows join is not a function . Whenever I add a new recipe with my AddRecipe component
3

You can use if expression or ternary operator:

<span>
    {
      testArray.length ? testArray.map((itemTestArray) =>
      (<span> {itemTestArray} </span>)) : '-'
    }
</span>

Comments

3

Map may be within Map. Ex:

import React from "react";
import PropTypes from "prop-types";
import { Row, Col } from "antd";

class Servers extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            items: [
                {
                    server: "Server 1",
                    status: "running",
                    appList: ["PL", "AM", "IM"]
                },
                {
                    server: "Server 2",
                    status: "running",
                    appList: ["PL", "AM"]
                },
                {
                    server: "Server 3",
                    status: "warning",
                    appList: ["PL", "AM", "IM"]
                },
                {
                    server: "Server 4",
                    status: "offline",
                    appList: ["PL", "AM", "IM"]
                },
                {
                    server: "Server 5",
                    status: "running",
                    appList: ["PL", "IM"]
                },
                {
                    server: "Server 6",
                    status: "running",
                    appList: ["PL", "AM", "IM"]
                },
                { server: "Server 7", status: "running", appList: ["PL"] },
                {
                    server: "Server 8",
                    status: "running",
                    appList: ["PL", "AM", "IM"]
                },
                {
                    server: "Server 9",
                    status: "running",
                    appList: ["PL", "AM", "IM"]
                },
                {
                    server: "Server 10",
                    status: "running",
                    appList: ["PL", "AM", "IM"]
                },
                {
                    server: "Server 11",
                    status: "running",
                    appList: ["PL", "AM", "IM"]
                },
                {
                    server: "Server 12",
                    status: "running",
                    appList: ["PL", "AM", "IM"]
                }
            ]
        };
    }

    render() {
        return (
            <React.Fragment>
                <Row type="flex" justify="space-around" align="middle">
                    {this.state.items.map(item => (
                        <Col span={5} className="box">
                            <div className={["server", item.status].join(" ")}>
                                <ul>
                                    <li />
                                    <li />
                                    <li />
                                </ul>
                            </div>
                            <ul className="appList">
                                {item.appList.map(app => (
                                    <li>{app}</li>
                                ))}
                            </ul>
                            <h6 className="server-name">{item.server}</h6>
                        </Col>
                    ))}
                </Row>
            </React.Fragment>
        );
    }
}

Servers.propTypes = {
    children: PropTypes.any
};

export default Servers;

Comments

2

If it's a simple array of strings you can use join

const myArr = ['hello', 'world'];
const stringifyArr = myArr.join(', ');
console.log(stringifyArr) // 'hello, world'

Comments

1

Either you can use map for that also, like this:

{
    this.state.recipes.map(recipe => {
        return ( 
            <div key={recipe.name}>
                <dt>{recipe.name}</dt>
                {
                   recipe.ingredient && recipe.ingredient.map(el => <dd key={el}> {el} </dd>)
                }
                <hr></hr>
            </div>
        )
    })
}

Or join the array using , , like this:

<dd> {recipe.ingredient.join(',')} </dd>

Check this working example:

let data =  [ 
{
  name : 'chicken',
  ingredient : ['spinach','chillies']
}];    
  
class App extends React.Component {
    constructor(props){
    super(props);
       this.state={ recipes :[] } 
       this.addRecipe=this.addRecipe.bind(this);
    }

    addRecipe (recipe) {
      this.setState({ 
         recipes: [...this.state.recipes, recipe]
      });
    }
    componentWillMount(){
      this.setState({
        recipes : data
      });
    } 
    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.join(',')}</dd>
                 <hr></hr>
                </div>
               )
             })
         }
      </dl>
     
        Add Recipe
        <AddRecipe addRecipe={this.addRecipe}/>
      </div>
    );
 }
}

class AddRecipe extends React.Component{
   add(){
      this.props.addRecipe({name: this.name.value, ingredient: this.ing.value.split(',')});
   }
   render(){
      return (
         <div>
           <input ref={name=>this.name=name}/>
           <input ref={ing=>this.ing=ing}/>
           <input type='button' onClick={this.add.bind(this)} value='Add'/>
         </div>
      )
   }
}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='root'/>

4 Comments

This shows .map is not a function whenever I add a new recipe with my AddRecipe component.
just put the check, before using map.
what check? What should I do for this?
check the updated answer, created a sample working solution, values in ingredient input element should be , separated, run the above snippet and check :)
0

You can try this.

{recipe.ingredient.join(",")}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.