-1

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
Waqas
  • 1
  • additional hint: try to avoid using the index as a key in jsx if possible. https://reactjs.org/docs/lists-and-keys.html#keys – PRSHL Jul 24 '22 at 17:57

2 Answers2

0

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

hgb123
  • 13,869
  • 3
  • 20
  • 38
0

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}/>
  })}
Nathan
  • 73,987
  • 14
  • 40
  • 69