1. Conditional Rendering 이란?
- Conditional Rendering
조건부 렌더링= 특정 조건에 따라 다른 결과물을 렌더링 하는 것- JSX 에서 null, false, undefined 를 렌더링하게 된다면 아무것도 나타나지 않음
- React의 조건부 렌더링은 JS랑 똑같이 동작함
- if 또는 조건 연산자같은 JS 연산자를 사용하여 현재 상태를 나타내는 요소를 만들고,
- 이에 맞게 React가 UI를 업데이트함
- 조건부 렌더링하는 방법
- 삼항연산자 사용
1function Hello({ color, name, isSpecial }) {2// isSpecial 값이 true 라면 <b>*</b> 를, 그렇지 않다면 null3return (4<div style={{ color }}>5{isSpecial ? <b>*</b> : null}6안녕하세요 {name}7</div>8)9}
2. Truthy and Falsy
Truthy: true 같은 값을 가지는 것- e.g.
true, {}, [], 42, -42, “0”, “false”, new Date(), Infinity, 3.14 - MDN Truthy
- e.g.
Falsy: false 같은 값을 가지는 것- e.g.
false, null, undefined, 0, -0, NaN, “” - MDN Falsy
- e.g.
1function print(person) {2console.log(person.name)3}45const person = {6name: '메시',7}89// print함수의 파라미터가 비어있으면 에러💥10print() // TypeError: Cannot read property 'name' of undefined
만약에 다음과 같이 print 에 null 값이 파라미터로 전달되면 어떨까요?
1function print(person) {2if (person === undefined) {3console.log('person이 없네요')4return5}6console.log(person.name)7}89const person = null10print(person) // TypeError: Cannot read property 'name' of null
person 이 undefined 이거나, null 인 상황을 대비하려면 다음과 같이 코드를 작성합니다.
1function print(person) {2if (person === undefined || person === null) {3console.log('person이 없네요')4return5}6console.log(person.name)7}89const person = null10print(person)
2.1 undefined와 null인 경우
위 코드는 다음과 같이 축약해서 작성 할 수 있습니다.
1function print(person) {2// 1. undefined 와 null 은 Falsy 한 값3// 2. Falsy 한 값 앞에 느낌표를 붙여주면 true 로전환4if (!person) {5// <- 📝 person이 undefined나 null인 경우6console.log('person이 없네요')7return8}9console.log(person.name)10}1112const person = null13print(person)
2.2 if문에서 Truthy 한 값 체크
Truthy 한 값과 Falsy 한 값은 if 문에서도 사용 가능
1const value = { a: 1 }23// 1. value 가 Truthy 한 값이기 때문에, 콘솔에 메시지가 출력됨4// 2. 반면, value 가 null, undefined, 0, '', NaN 중 하나라면, 나타나지 않음5if (value) {6console.log('value 가 Truthy 하네요.')7}
3. short-circuit evaluation(단축평가 계산)
3.1 AND, OR 연산자
1// 📝 AND(&&) 연산자2true && true // true3true && false // false45// 📝 OR(||) 연산자6true || false // true7false || true // true
3.2 if문에서 Truthy 한 값 체크
예를 들어, 다음과 같은 코드가 있다고 가정합니다.
1const dog = {2name: '멍멍이',3}45function getName(animal) {6// 2. animal 객체가 undefined 이기 때문에7return animal.name // 3. undefined 에서 name 값을 조회 할 수 없어서 에러 발생😭8}910// 1. getName의 파라미터에 제대로된 객체가 주어지지 않으면?11const name = getName()12console.log(name)
함수에서 animal 값이 제대로 주어졌을 때만 name을 조회하고, 그렇지 않을때는 그냥 undefined를 반환하게 하고 싶으면?
1function getName(animal) {2// animal 값이 제대로 주어졌을 때만 name을 조회3// animal 값이 없으면 undefined 반환4if (animal) {5return animal.name6}7return undefined8}
3.3 && 연산자로 코드 단축
1const dog = {2name: '멍멍이',3}45function getName(animal) {6// animal 값이 제대로 주어졌을 때만 animal.name 반환7// animal 값이 없으면 undefined 반환8return animal && animal.name9}1011const name = getName()12console.log(name) // undefined
추가 예시
1console.log(true && 'hello') // hello2console.log(false && 'hello') // false3console.log('hello' && 'bye') // bye4console.log(null && 'hello') // null5console.log(undefined && 'hello') // undefined6console.log('' && 'hello') // ''7console.log(0 && 'hello') // 08console.log(1 && 'hello') // hello9console.log(1 && 1) // 1
3.4 || 연산자로 코드 단축
만약 어떤 값이 Falsy 하다면 대체로 사용할 값을 지정해줄 때, 사용 가능
1function getName(animal) {2const name = animal && animal.name3if (!name) {4return '이름이 없는 동물입니다'5}6return name7}
위 코드는 || 연산자를 사용하면 다음과 같이 단축시킬 수 있습니다.
1function getName(animal) {2const name = animal && animal.name34// name이 falsy한값이라면, ||의 오른쪽의 값 출력5return name || '이름이 없는 동물입니다.'6}
4.. Conditional Rendering
보통 삼항연산자를 사용한 조건부 렌더링을 주로 특정 조건에 따라 보여줘야 하는 내용이 다를 때 사용합니다.
1function Hello({ name, isSpecial }) {2// isSpecial이 false일땐 false이고, isSpecial이 true 일 땐 <b>*</b>3return (4<>5{isSpecial && <b>*</b>}6안녕하세요 {name}7</>8)9}
4.1 props 값 설정을 생략하면 =
컴포넌트의 props 값을 설정하게 될 때 만약 props 이름만 작성하고 값 설정을 생략한다면, 이를 true 로 설정한 것으로 간주함
1function App() {2return (3<>4{/* isSpecial 이름만 넣어주면 isSpecial={true}와 동일한 의미 */}5<Hello name="react" color="red" isSpecial />6<Hello color="pink" />7</>8)9}