본문 바로가기
JavaScript/React

[ReactJS_Complete] Outputting Conditional Content

by HJ0216 2023. 5. 31.

이 글은 [[한글자막] React 완벽 가이드 with Redux, Next.js, TypeScript]를 수강하며 정리한 글입니다.

 

 

⚛️ 기본 환경: IDE: VS code, Language: React

 

 

조건문 출력

1. 3항 연산자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const Expenses = (props) => {
  return (    
    {filteredExpenses.length === 0 ? (
      <p>No Expenses found</p>
    ) : (
      filteredExpenses.map((expense) => (
        <ExpenseItem
          key={expense.id}
          title={expense.title}
          amount={expense.amount}
          date={expense.date}
        />
      ))
    )}
  );
};
 
 
cs

 

2. && 연산자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const Expenses = (props) => {
  return (            
    {filteredExpenses.length === 0 && <p>No Expenses found</p>}
    {filteredExpenses.length > 0 && (
      filteredExpenses.map((expense) => (
        <ExpenseItem
          key={expense.id}
          title={expense.title}
          amount={expense.amount}
          date={expense.date}
        />
      ))
    )}
  );
};
 
 
cs

 

 

3. 변수 선언

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const Expenses = (props) => {
 
  let expensesContent = <p>No Expenses found</p>;
 
  if(filteredExpenses.length>0){
    expensesContent = filteredExpenses.map((expense) => (
      <ExpenseItem
        key={expense.id}
        title={expense.title}
        amount={expense.amount}
        date={expense.date}
      />
    ));
  }
 
  return (
    {expensesContent}
  );
};
 
 
cs