Melissa Stewart
Melissa Stewart

Reputation: 3605

Mapping array to components fails in react

I've a MealList component which lists an array of Meal components.

const MealList = (props) => {
    console.log(props.meals);// [Array(3)]

    return (
        <div style={{width: '70%'}}>
            <h3 style={{color: 'grey', fontSize: '1.4em', fontWeight: '700', marginBottom: '1em'}}><FontAwesomeIcon
                icon={faPlusCircle} style={{color: '#007bff', marginRight: '0.5em'}}/> ADD MEAL</h3>
            <Table striped bordered hover>
                <thead>
                <tr>
                    <th>#</th>
                    <th>Meal</th>
                    <th>Calories</th>
                    <th>Time</th>
                    <th>Date</th>
                    <th>Update</th>
                    <th>Delete</th>
                </tr>
                </thead>
                <tbody>
                    {props.meals.map(meal => <Meal label={meal.label} calories={meal.calories} time={meal.time}
                                               date={meal.date}/>)}
                </tbody>
            </Table>
        </div>

    )
};
export default MealList;

This is the structure of the array on the console.

[Array(3)]
0: Array(3)
0: {id: 8, label: "Breakfast", calories: 311, time: "20:10:00", date: "2019-12-29", …}
1: {id: 9, label: "Lunch", calories: 721, time: "20:10:00", date: "2019-12-29", …}
2: {id: 10, label: "Dinner", calories: 663, time: "20:10:00", date: "2019-12-29", …}
length: 3

Inside the Meal component though the props value render undefined.

const Meal = (props) => {
    console.log(props.label, props.calories, props.time, props.data);//undefined ....

    return (<tr>
        <td>1</td>
        <td>{props.label}</td>
        <td>{props.calories}</td>
        <td>{props.time}</td>
        <td>{props.date}</td>
        <td><FontAwesomeIcon icon={faUserEdit}/></td>
        <td><FontAwesomeIcon icon={faMinusCircle}/></td>
    </tr>);
};
export default Meal;

What am I doing wrong here?

Upvotes: 1

Views: 56

Answers (2)

rehab hussien Ali
rehab hussien Ali

Reputation: 89

I would suggest the following:

  • In the meal list component, before mapping on the props.meal check first if props.meal is not null otherwise show a message or something
  • [array[3]] means that the meal has one element which is an array of 3 elements, so try to adjust the structure of the data you are sending to the meals list
  • try to send to the meal component a meal object rather then meal.label , meal.date and so on, this way you have completely isolated reusable components

Upvotes: 1

skyboyer
skyboyer

Reputation: 23705

According to

[Array(3)]

your props.meals is not array of objects but array(with single element) of array of objects.

So while quickfix would be

{props.meals[0].map(meal =>

better to check why it's coming in different structure rather you expect

Upvotes: 1

Related Questions