Home > Software design >  How to map in react js
How to map in react js

Time:08-05

In my code I am using map to call my Expense-Item component and if I console I am getting all the values but this is not rendering means it shows nothing on output screen:

import React from 'react';
import ExpenseItem from './ExpenseItem';
import Card from '../UI/Card';
import './Expenses.css';
import { useState } from 'react';
import ExpensesFilter from './ExpenseFilter';


const Expenses = (props) => {
  const [filterYear, setFilterYear] = useState("2020");

  const FilterChangeHandler = (filter)=>{
      setFilterYear(filter);
  }

  return (
    <Card className="expenses">
      <ExpensesFilter selected={ filterYear } onFilterChangeHandler = { FilterChangeHandler }/>
      {props.items.map( (expense) =>{
            <ExpenseItem
                title={expense.title}
                amount={expense.amount}
                date={expense.date}
            />
          } 
        )}
    </Card>
  );
}

export default Expenses;

CodePudding user response:

Including return you should also check if props.items not null and has length to map to avoid breaking UI in these cases. You should modify your code as this,

return (
  <Card className="expenses">
    <ExpensesFilter
      selected={filterYear}
      onFilterChangeHandler={FilterChangeHandler}
    />
    {props.items && props.items.length > 0
      ? props.items.map((expense) => {
          return (
            <ExpenseItem
              title={expense.title}
              amount={expense.amount}
              date={expense.date}
            />
          );
        })
      : null}
  </Card>
);

CodePudding user response:

Add a return statement before your <ExpenseItem/> in order to return it from the .map()callback and render it. That‘s it.

  • Related