[React] 컴포넌트 조각화 & 조건 명령문 반환(return)하기

summereuna🐥·2023년 3월 16일
0

React JS

목록 보기
36/69

Expenses 컴포넌트를 좀 더 깔끔하게 사용하기 위해 let expenseContent 부터 if문을 따로 떼어보자!

📍Expenses.js

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;
  1. ExpensesList.js 파일을 만든다.
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;
  1. Expenses.js
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;
profile
Always have hope🍀 & constant passion🔥

0개의 댓글