Expenses 컴포넌트를 좀 더 깔끔하게 사용하기 위해 let expenseContent 부터 if문을 따로 떼어보자!
import Card from "../UI/Card";
import "./Expenses.css";
import ExpenseItem from "./ExpenseItem";
import ExpensesFilter from "./ExpensesFilter";
import { useState } from "react";
const Expenses = (props) => {
const [filteredYear, setFilteredYear] = useState("2020");
const filterChangedYearHandler = (selectedYear) => {
setFilteredYear(selectedYear);
};
const filteredExpenses = props.items.filter(
(expense) => expense.date.getFullYear().toString() === filteredYear
);
// 🔥 여기서부터
let expenseContent = <div>지출한 비용이 없습니다.</div>;
if (filteredExpenses.length > 0) {
expenseContent = filteredExpenses.map((expenses) => (
<ExpenseItem
key={expenses.id}
id={expenses.id}
title={expenses.title}
amount={expenses.amount}
date={expenses.date}
/>
));
}
// 🔥 여기까지
return (
<Card className="expenses">
<ExpensesFilter
onChangeFilterYear={filterChangedYearHandler}
selected={filteredYear}
/>
// 🔥
{expenseContent}
</Card>
);
};
export default Expenses;
import ExpenseItem from "./ExpenseItem";
import "./ExpensesList.css";
//렌더링을 위한 별개의 로직 사용(이렇게 따로 컴포넌트를 만들면 조건문을 이런식으로 사용할 수도 있다!)
const ExpensesList = (props) => {
//비용이 없으면 h2 태그 렌더링하도록 h2 리턴시키기
if (props.filteredExpenses.length === 0) {
return <h2 className="expenses-list__fallback">지출한 비용이 없습니다.</h2>;
}
//비용 있으면 ExpenseItem 컴포넌트에 비용 데이터 매핑하여 렌더링
return (
<ul className="expenses-list">
{props.filteredExpenses.map((expenses) => (
<ExpenseItem
key={expenses.id}
id={expenses.id}
title={expenses.title}
amount={expenses.amount}
date={expenses.date}
/>
))}
</ul>
);
};
export default ExpensesList;
import Card from "../UI/Card";
import "./Expenses.css";
import ExpensesFilter from "./ExpensesFilter";
import { useState } from "react";
import ExpensesList from "./ExpensesList";
const Expenses = (props) => {
const [filteredYear, setFilteredYear] = useState("2020");
const filterChangedYearHandler = (selectedYear) => {
setFilteredYear(selectedYear);
};
const filteredExpenses = props.items.filter(
(expense) => expense.date.getFullYear().toString() === filteredYear
);
return (
<Card className="expenses">
<ExpensesFilter
onChangeFilterYear={filterChangedYearHandler}
selected={filteredYear}
/>
// 🔥 ExpensesList 컴포넌트에 필터된 비용 배열(filteredExpenses)을 props으로 보낸다.
{<ExpensesList filteredExpenses={filteredExpenses} />}
</Card>
);
};
export default Expenses;