0

I want to pass data from props into another component but I'm having trouble passing data from a nested array. My JSON has the following structure:

[
  {
    id: 1,
    category: "Fish",
    nodes: [
      {
        id: 1,
        title: "Bacalhau com broa",
        ingredients: [
          "bacalhau",
          "broa"
        ]
      },
      {
        id: 2,
        title: "Bacalhau à Zé do Pipo",
        ingredients: [
          "bacalhau",
          "broa",
          "5 cebolas"
        ]
      },
    ],
  }
];

and I've tried the following, where dishesData contains the nodes from the JSON:

        {dishesData.map((dishes) => {
          dishes.forEach((dish) => {
            console.log(dish.title)
            return <Dish title={dish.title} ingredients={dish.ingredients} />;
          });          
        })}

The console.log(dish.title) is printing the correctly but not rendering my component to the page.

1
  • What's not rendering? The console log? Commented Feb 3, 2021 at 16:32

2 Answers 2

1

your return statement is inside forEach so it won't work, you need to return the value to the parent map function:

{dishesData.map((dishes) => {
  return dishes.map((dish) => {
    return <Dish title={dish.title} ingredients={dish.ingredients} />;
  });          
})}
Sign up to request clarification or add additional context in comments.

Comments

0
import React from 'react';

// Json data 
const dishesData = [
  {
    id: 1,
    category: "Fish",
    nodes: [
      {
        id: 1,
        title: "Bacalhau com broa",
        ingredients: [
          "bacalhau",
          "broa"
        ]
      },
      {
        id: 2,
        title: "Bacalhau à Zé do Pipo",
        ingredients: [
          "bacalhau",
          "broa",
          "5 cebolas"
        ]
      },
    ],
  }
];


// First component - I have used a functional component 
const ComponentOne = (props) => {
  // output: Bacalhau com broa, Bacalhau à Zé do Pipo
  const answer = dishesData.map(dishes => {
    dishes.nodes.map(dish=> dish.title)
  });
  
  // a title prop is pased to ComponentTwo component
  return (
      <ComponentTwo title = {answer} />
  );
}


// Another component that will receive our props passed to it

const ComponentTwo = (props) => {
  console.log(props.title)
  return (
    <p> {props.title} </p>
   )
}

export default ComponentOne;

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.