Conditional-rendering(조건부 렌더링)
Conditional-rendering(조건부 렌더링)란?
- 특정 조건에 따라 다른 컴포넌트를 렌더링 하는 것
- 예를 들어, 데이터가 로딩 중 일 때, 데이터가 없을때 등등 다양한 상황에서 조건식에 따라 다른 컴포넌트를 렌더링 할 때 사용
- 기본적인 자바스크립트에서 제공하는 조건문인 if/else, switch/case 등이 있음
조건부 렌더링 방법
① if / else
- 가장 기본적인 방법
- 컴포넌트 props 값에 따라 리턴하는 리액트 컴포넌트를 분기 처리함
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ConditionalRendering = ({ loading, data }) => { | |
if (loading) { | |
return <Loading />; | |
} | |
return <div>{data}</div>; | |
}; |
② switch / case
- 조건이 다양할 때 사용
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Board({ type, ...rest }) => { | |
switch(type) { | |
case 'edit': | |
return <EditBoard {...rest} />; | |
case 'delete': | |
return <DeleteBoard {...rest} />; | |
case 'list': | |
return <ListBoard {...rest} />; | |
default: | |
return null; | |
} | |
}; |
③ 논리 연산자(&&)
- 논리 연산자 &&를 사용
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{data && data.fetchProduct && data.fetchProduct.name} |
┌ ⓐ data가 참일 때 : && 뒤의 data.fetchProduct가 렌더링 됨
├ ⓑ data, data.fetchProduct가 참일 때 : && 뒤의 data.fetchProduct.name가 렌더링 됨
└ ⓒ data가 거짓일 때 : && 앞의 data가 렌더링 됨
④ 삼항 연산자
- 자바스크립트의 삼항 연산자인 condition ? true : false 를 사용
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{data ? data.fetchProduct.name : "loading..."} |
└ data가 참이라면 data.fetchProduct.name을 렌더링하고, 거짓이라면 "loading..."을 렌더링한다.
⑤ 옵셔널 체이닝(optional chaining)
- 옵셔널 체이닝(optional chaining)은 ES2020에서 등장한 새로운 연산자로 좀 더 간결하게 사용할 수 있음
- 삼항 연산자, && 연산자와 똑같은 기능
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{data ?. fetchProduct ?. name} |
┌ data가 존재하지 않아도 undefined가 반환되어 에러가 발생하지 않음
└ 하지만 data가 없는지, fetchProduct가 없는지, 어디에서 오류가 발생한지 찾기가 어려워지는 단점이 있음
'React > 2022-上' 카테고리의 다른 글
container-presentation (0) | 2022.03.27 |
---|---|
Destructuring Assignment (구조 분해 할당) (0) | 2022.03.27 |
Static, Dynamic Routing (정적 라우팅, 동적 라우팅) (0) | 2022.03.27 |
try ~ catch (0) | 2022.03.26 |
Async / Await (0) | 2022.03.26 |