Home > Software engineering >  How to use map method in reactjs
How to use map method in reactjs

Time:07-25

Output is not showing in the browser while using map method but it is showing while calling elements one by one from array. Answer please

const App = () => {
  const items = [
    {
      title:"University Expenses",
      amount:267
    },
    {
      title:"Car Insurance",
      amount:1200
    },
    {
      title:"Bike Expenses",
      amount:5000
    }
  ]
  return(
    <>
  {items.map(( val , i )=>{
      <ExpenseItem key={i} title = {val.title} amount = {val.amount}/>
  })}
  </>
  )
}

Code of ExpenseItem component

import React from "react";

const ExpenseItem = (props) => {
  return (
    <>
      <div className="expense_div">
         <h2>{props.title}</h2> 
        <div>
          <button>${props.amount}</button>
        </div>
      </div>
    </>
  )
};

export default ExpenseItem

CodePudding user response:

Since you did not return anything in the map's callback function, the components rendered a list of undefined. The solution is to return appropriated values in the map callback function (here is the ExpenseItem component)

return (
    <>
  {items.map(( val , i )=>{
      return <ExpenseItem key={i} title = {val.title} amount = {val.amount}/>
  })}
  </>
)

or shorthand, notice the () bracket

return (
    <>
  {items.map(( val , i )=>(
      <ExpenseItem key={i} title = {val.title} amount = {val.amount}/>
  ))}
  </>
)

References

Array map method

Arrow function

CodePudding user response:

You're very close, the issue is here:

  {items.map(( val , i )=>{
      <ExpenseItem key={i} title = {val.title} amount = {val.amount}/>
  })}

In an arrow function, when you put brackets after the arrow that means you're wanting to execute multiple lines of code, and need an explicit return. If you use parentheses instead, it's an expression that returns automatically. See here

So what you want is either

  {items.map(( val , i )=>(
      <ExpenseItem key={i} title = {val.title} amount = {val.amount}/>
 ))}

Or

  {items.map(( val , i )=>{
      return <ExpenseItem key={i} title = {val.title} amount = {val.amount}/>
  })}
  • Related