Uncaught Error: Objects are not valid as a React child (found: [object Date]). If you meant to render a collection of children, use an array instead

Viewed 47

I was making a simple app on react and I used the contents of the expenses array in the ExpenseItem component and it shows this error. I dont really understand what the problem with my code is. Below is the code for the App component where I used the ExpenseItem component and the code for that is absolutely fine.

    import React from "react";
import ExpenseItem from "./components/ExpenseItem";

function App() {
  const expenses = [
    {
      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>
      <h2>Let's get started!</h2>
      <ExpenseItem title={expenses[0].title} amount={expenses[0].amount} date={expenses[0].date}/>
      <ExpenseItem title={expenses[1].title} amount={expenses[1].amount} date={expenses[1].date}/>
      <ExpenseItem title={expenses[2].title} amount={expenses[2].amount} date={expenses[2].date}/>
      <ExpenseItem title={expenses[3].title} amount={expenses[3].amount} date={expenses[3].date}/>
    </div>
  );
}

export default App;

ps: Below is the code for Expense Item

import React from "react";
import classes from "./ExpenseItem.module.css"

function ExpenseItem(props) {
  return (
    <div className={classes["expense-item"]}>
      <div>{props.date}</div>
      <div className={classes["expense-item__description"]}>
        <h2>{props.title}</h2>
        <div className={classes["expense-item__price"]}>{props.amount}</div>
      </div>
    </div>
  );
}

export default ExpenseItem;
1 Answers

So, the issue is inside ExpenseItem component. You cannot render date objects in this way, react has no idea about how to render it. So just add a dateString useMemo string variable to convert the date object passed to the format you want. I used ISO format as an example:

function ExpenseItem({ date, title, amount }) {
  const dateString = useMemo(() => {
    if (!date) return "";
    return date.toISOString();
  }, [date]);

  return (
    <div className={classes["expense-item"]}>
      <div>{dateString}</div>
      <div className={classes["expense-item__description"]}>
        <h2>{title}</h2>
        <div className={classes["expense-item__price"]}>{amount}</div>
      </div>
    </div>
  );
}
Related