[React] Conditional Rendering

J.·2024년 5월 18일

React

목록 보기
7/11
post-thumbnail

🔍 한눈에 알아보기

Conditional Rendering

  • 조건부 렌더링

Truthy / Falsy

  • true/false는 아니지만 true/false로 여겨지는 값
// truthy
true
{} (empty object)
[] (empty array)
73 (number, not zero)
"0", "false" (string, not empty)

// falsy
false
0, -0 (zero, minus zero)
0n (BigInt zero)
'', "", `` (empty string)
null
undefined
NaN (not a number)

Element Variables

  • 엘리먼트 변수
  • 엘리먼트를 변수처럼 사용
// 'button'이라는 변수 안에 엘리먼트를 넣어서 사용

let button;
if (isLoggedIn) {
	button = <button onClick={handleLogoutClick}>Logout</button>
}
else{
	button = <button onClick={handleLoginClick}>Login</button>
}

return(
	<div>
    	{button}
    </div>
)

Inline Conditions

  • 조건문을 코드안에 집어넣는 것

Inline If

  • && 연산자
  • Short-circuit evaluation (단축 평가)

    true && expression -> expression
    false && expression -> false

// 읽지 않은 메시지가 0보다 클 때만 출력

<div>
	{unreadMessages.length > 0 && 
    	<h2>
        	읽지 않은 메시지가 있습니다.
        </h2>
    }
</div>

Inline If-Else

  • ? 연산자 사용
  • 3항 연산자

    condition ? true : false

// 'isLoggedIn'이라는 boolen 형태의 로그인 상태를 나타내는 변수의 값에 따라
// 로그인/로그아웃 버튼 컴포넌트를 출력

<div>
	{isLoggedIn ? <LogoutButton/> : <LoginButton/>}
</div>

Component 렌더링 막기

  • null을 return하면 렌더링 되지 않음
function WarningBanner(props){
	if (!props.warning) { // boolen 값이 false일 때
    	return null; // null을 return해서 출력 방지
    }
    
    return ( // true면 출력
    	<div>Warning</div>
    )
}
profile
코린이 (코인 어린이 아니라 코딩 어린이임)

0개의 댓글