Home > Software design >  Can't dynamically render reactjs elements using .map()
Can't dynamically render reactjs elements using .map()

Time:05-18

I am trying to dynamically render out ingredient/qty/measure using .map() in reactjs I am following a few tutorials online but unable to properly implement the code in my own code.

Here is the error I am currently getting:

react-dom.development.js:86 Warning: Functions are not valid as a React child. 
This may happen if you return a Component instead of <Component /> from render. 
Or maybe you meant to call this function rather than return it.

Here is the data I am trying to map over:

recipeIngredients: Array(2)
0: {name: 'lemon', quantity: '100', measure: 'g'}
1: {name: 'butter', quantity: '5', measure: 'cups'}

Here is my code:

import './IngredientsList.css'

let ingredientArray
function mapIngredients() {
  ingredientArray.map((item) => (
    <div className="ingredient-element">{item}</div>
  ))
}

function IngredientsList(props) {
  console.log(props)
  ingredientArray = props.recipeIngredients

  return <div className="ingredient-list">{mapIngredients}</div>
}

export default IngredientsList

Basically, trying to render out the following set of divs (recipeIngredients.name has an additional class):

<div className="ingredient-list">
    <div className="ingredient-element">recipeIngredients.quantity</div>
    <div className="ingredient-element">recipeIngredients.measure</div>
    <div className="ingredient-element ingredient-name">recipeIngredients.name</div>
  </div>

I notice that the () are missing from the IngredientList function - VSCode keeps deleting them when I save the code so I can't manually add them...

CodePudding user response:

You forgot to invoke the function. Here you're trying to render the function itself:

return <div className="ingredient-list">{mapIngredients}</div>

Instead, invoke the function and render its result:

return <div className="ingredient-list">{mapIngredients()}</div>

Additionally, the function currently doesn't return anything. Add a return statement:

function mapIngredients() {
  return ingredientArray.map((item) => (
    <div className="ingredient-element">{item}</div>
  ))
}

CodePudding user response:

I'm seeing two issues here. First, you're not invoking the function(as you said that vs code is not letting you do that). The second is item is an object here. Try this instead:-

function IngredientsList(props) {
  console.log(props)
  ingredientArray = props.recipeIngredients || [];

  return (
    <div className="ingredient-list">
      {
        ingredientArray.map(item => (
          <div className="ingredient-element">{item.name}</div>
        ))
      }
    </div>
  )
}
  • Related