본문 바로가기

Study/React

Conditional contents

&& operator 

const Expenses = (props) => {
  const [filterYear, setFilterYear] = useState('2022');
  
  const filterd = props.expenses //
    .filter((item) => item.date.getFullYear().toString() === filterYear);

  return (
    <main className='container expenses'>
      <Filter setFilterYear={setFilterYear} selectedYear={filterYear} />
      {filterd.length === 0 && <p>no item</p>}
      {filterd.length !== 0 &&
        filterd.map((item) => (
          <ExpenseItem
            key={item.id}
            title={item.title}
            amount={item.amount}
            date={item.date}
          />
        ))}
    </main>
  );
};

 

if

const Expenses = (props) => {
  const [filterYear, setFilterYear] = useState('2022');
  
  const filterd = props.expenses 
    .filter((item) => item.date.getFullYear().toString() === filterYear);
  
  // this is possible! 
  let expenses = <p>no item<p>; 
  
  if(filterd.length > 0) {
    expenses = filterd.map((item) => (
          <ExpenseItem
            key={item.id}
            title={item.title}
            amount={item.amount}
            date={item.date}
          />
        ))
  }

  return (
    <main className='container expenses'>
      <Filter setFilterYear={setFilterYear} selectedYear={filterYear} />
      {expenses}
    </main>
  );
};

'Study > React' 카테고리의 다른 글

Fragment & Portal  (0) 2022.06.18
Component Styling  (0) 2022.06.18
Dynamic List  (0) 2022.06.17
prevState  (0) 2022.06.16
Event & useState  (0) 2022.06.16