Cannot read property '0' of undefined

import ExpenseItem from './ExpenseItem.';
import './Expenses.css';

function Expenses (props) { 
    const expenses1 = [
        {
          id: 'e1',
          title: 'Toilet Paper',
          amount: 94.12,
          date: new Date(2020, 7, 14),
        },
        { id: 'e2', title: 'New TV', amount: 799.49, date: new Date(2021, 2, 12) },
        {
          id: 'e3',
          title: 'Car Insurance',
          amount: 294.67,
          date: new Date(2021, 2, 28),
        },
        {
          id: 'e4',
          title: 'New Desk (Wooden)',
          amount: 450,
          date: new Date(2021, 5, 12),
        },
      ];
    
     return (
     <div className="expenses"> 
        <ExpenseItem 
        title={props.item[0].title}
        amount={props.item[0].amount}
        date={props.item[0].date} 
        ></ExpenseItem>
        <ExpenseItem
         title={props.item[1].title}
         amount={props.item[1].amount}
         date={props.item[1].date} 
        ></ExpenseItem>
        <ExpenseItem
         title={props.item[2].title}
         amount={props.item[2].amount}
         date={props.item[2].date} 
        ></ExpenseItem> 
        <ExpenseItem
         title={props.item[3].title}
         amount={props.item[3].amount}
         date={props.item[3].date} 
        ></ExpenseItem>  
    </div>
    );
} 

export default Expenses;

It would be nice with some context and an actual question. But whatever.

We have to see how you are using the component and what props you are passing it. The error message is saying you can’t access index 0 on something that is undefined. Which suggests an issue with what or how you are passing the props to the component.

Try logging props inside the component to check it.

Take your data (expenses1) out of your Expenses function and declare it else where (another file would be good). Import your Expenses function & expenses1 data into the same file and when you use Expenses it would look like this:

<Expenses item={expenses1} />

That would let you pass the data in as a prop to your Expenses function. Hope that helps!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.