0

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;
1
  • Your callback in map is wrong, you have to put return. i.e. => {return <ExpenseItem... } Commented Aug 4, 2022 at 15:54

2 Answers 2

1

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>
);
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.