Reputation: 25
This is my code in "App.js" as the array I want to loop from, I wanted to loop from the array below and output the contents of it in the browser with a table.
This is my return
return (
<div className="container">
<h1> Expenses </h1>
<table className="table table-bordered">
<tr>
<th>Title</th>
<th>Amount</th>
<th>Date</th>
</tr>
{expenses.map((expense, index) => (
<tr data-index={index}>
<td>{expense.title}</td>
<td>{expense.amount}</td>
<td>{expense.date}</td>
</tr>
))}
</table>
</div>
);
This is the code from my component.
import './ExpenseItem.css';
function ExpenseItem(props) {
return (
<div className="expense-item" >
<div>{props.date.toISOString()}</div>
<div className="expense-item__description">
<h2>{props.title}</h2>
<div className="expense-item__price">{props.amount}</div>
</div>
</div>
)
}
export default ExpenseItem
This is the error that I am getting.
Upvotes: 0
Views: 523
Reputation: 21
I think in App.js when you loop through the expenses array, you want to return the ExpenseItem component, passing it the current expense item as a prop, like this:
{expenses.map((expense, index) => (
<ExpenseItem item={expense} />
))}
And in ExpenseItem, since props is an object, you should change props.title
to props.item.title
etc.
Hope this helps!
Upvotes: 0
Reputation: 51
return (
<div className="container">
<h1> Expenses </h1>
<table className="table table-bordered">
<tr>
<th>Title</th>
<th>Amount</th>
<th>Date</th>
</tr>
{expenses.map((expense, index) => (
<tr data-index={index}>
<td>{expense.title}</td>
<td>{expense.amount}</td>
<td>{expense.date.toISOString()}</td>
</tr>
))}
</table>
</div>
);
Date object is not valid react child.
Upvotes: 0
Reputation: 218818
You're trying to output a Date
object:
<td>{expense.date}</td>
Which, as the error states, is an object and not a simple value. So React has no way of knowing how to display it.
You can define the format and output that. For example:
<td>{expense.date.toLocaleDateString()}</td>
There are a variety of functions built-in to the Date object to format it, or you can combine multiple values from it into a custom format, or use a date formatting/parsing library, etc.
Upvotes: 1