Instead of static way of creating components as we did before, we can use javascript Array built-in methods.
In this case, you can use '.map()'
{props.data.map((el) => {
return (
<ExpenseItem title={el.title} amount={el.amount} date={el.date} />
);
})}
If you wanna append item to a list and then re-evalute the list status, you need to set initial list outside of function first.
const initialExpenses = [
...items
];
and then In function, we should change the state of list whenever an item added.
const [expenses, setExpenses] = useState(initialExpenses);
const createNewExpenseHandler = (expenseData) => {
setExpenses((prevExpenses) => {
return [expenseData, ...prevExpenses];
});
};
we should use callback format in state function because the new list depends on previous list.
When you map out list without key prop for dynamic flow, React just visit existed items and update by changing them.
This may cause some bugs and performance is not good.
By setting key prop, you can help react to identify each items
{props.data.map((el) => (
<ExpenseItem
key={el.id}
title={el.title}
amount={el.amount}
date={el.date}
/>
))}
The id type is not important , you just can give any id to identify each items.(When we add Backend database, there may be given unique id in the databse)
We may not have data sometimes. In this case, we need condtional statement to give execption
{filteredList.length === 0 ? (
<p>No expenditures found</p>
) : (
filteredList.map((el) => (
<ExpenseItem
key={el.id}
title={el.title}
amount={el.amount}
date={el.date}
/>
))
)}
{filteredList.length === 0 && <p>No expenditures found</p>}
{filteredList.length > 0 &&
filteredList.map((el) => (
<ExpenseItem
key={el.id}
title={el.title}
amount={el.amount}
date={el.date}
/>
))}
let expensesContent = <p>No expenditures found</p>;
if (filteredList.length > 0) {
expensesContent = filteredList.map((el) => (
<ExpenseItem
key={el.id}
title={el.title}
amount={el.amount}
date={el.date}
/>
));
}
return (
<Card className="expenses">
<ExpensesFilter
selected={filteredYear}
onFilterDate={filterDateHandler}
/>
{expensesContent}
</Card>
);
if (props.data.length === 0) {
return <h2 className="expense-list__fallback">Found no expenses.</h2>;
}
return (
<ul className="expensse-list">
{props.data.map((el) => (
<ExpenseItem
key={el.id}
title={el.title}
amount={el.amount}
date={el.date}
/>
))}
</ul>
);
};