skip to Main Content

How do i get the recipeName using .map() in React?

Below is my dummy data for the recipe.

const recipe = [
  {
    category: 'Keto',
    name: 'Chicken Bistek',
    calories: '500',
    description: '',
    recipes: [
      {
        recipeName: 'Chicken',
        recipeSize: '3 lbs',
      },
      {
        recipeName: 'Garlic',
        recipeSize: '4 cloves',
      },
      {
        recipeName: 'Onion',
        recipeSize: '1 whole',
      },
      {
        recipeName: 'Soy Sauce',
        recipeSize: '1/4 cup',
      },
      {
        recipeName: 'Coconut Oil',
        recipeSize: '1 tbsp',
      },
      {
        recipeName: 'Water',
        recipeSize: '1 cup',
      },
    ],
  },
];

I’ve tried this code below but it wont display the recipes array. It displays the name, category. But recipe.recipeName and recipe.recipeSize wont display in a tag.

const DietList = (props) => {
  return (
    <>
      {props.diets.map((diet) => (
        <div key={diet.name}>
          <a>{diet.name}</a>
          <a>{diet.category}</a>
          {diet.recipes.map((recipe) => (
            <a key={recipe.recipeName}>{recipe.recipeSize}</a>
          ))}
        </div>
      ))}
    </>
  );
};

2

Answers


  1. Your code is fine, just you are not displaying recipeName

    <>
       {props.diets.map((diet) => (
              <div key={diet.name}>
                <a>{diet.name}</a>
                <a>{diet.category}</a>
                <span>
                  {diet.recipes.map((recipe) => (
    // i added span so that we can add multiple tags
                    <span key={recipe.recipeName}> 
    
                      <a>{recipe.recipeSize}</a>
                      <a>{recipe.recipeName}</a> 
                    </span>
                  ))}
                </span>
              </div>
            ))}
          </>
    
    Login or Signup to reply.
  2. Here, I am making use of your dummy data:

    {
           recipe.map((item, index) => {
             return (
               <div key={index}>
                   <span>{item.category}</span>
                   <br />
                   <span>{item.name}</span>
                   <div>
                    {
                      item.recipes.map((r, index) => {
                        return (
                          <>
                            <span key={index} >{r.recipeName}: {r.recipeSize}</span><br />
                          </>
                        )
                      })
                    }
                   </div>
               </div>
             )
           })
         }
    

    I am not sure why you are using a tag. Unless, you are going to link it with a href tag.

    But I have used the return in the map, and it’s working fine. Hope, it will work for you too.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search