🎉 berenickt 블로그에 온 걸 환영합니다. 🎉
Front
05-조건부 렌더링

1. Conditional Rendering 이란?

  • Conditional Rendering
  • 조건부 렌더링 = 특정 조건에 따라 다른 결과물을 렌더링 하는 것
  • JSX 에서 null, false, undefined 를 렌더링하게 된다면 아무것도 나타나지 않음
  • React의 조건부 렌더링은 JS랑 똑같이 동작함
    • if 또는 조건 연산자같은 JS 연산자를 사용하여 현재 상태를 나타내는 요소를 만들고,
    • 이에 맞게 React가 UI를 업데이트함
  • 조건부 렌더링하는 방법
    • 삼항연산자 사용
1
function Hello({ color, name, isSpecial }) {
2
// isSpecial 값이 true 라면 <b>*</b> 를, 그렇지 않다면 null
3
return (
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
  • Falsy : false 같은 값을 가지는 것
    • e.g. false, null, undefined, 0, -0, NaN, “”
    • MDN Falsy
1
function print(person) {
2
console.log(person.name)
3
}
4
5
const person = {
6
name: '메시',
7
}
8
9
// print함수의 파라미터가 비어있으면 에러💥
10
print() // TypeError: Cannot read property 'name' of undefined

만약에 다음과 같이 print 에 null 값이 파라미터로 전달되면 어떨까요?

1
function print(person) {
2
if (person === undefined) {
3
console.log('person이 없네요')
4
return
5
}
6
console.log(person.name)
7
}
8
9
const person = null
10
print(person) // TypeError: Cannot read property 'name' of null

person 이 undefined 이거나, null 인 상황을 대비하려면 다음과 같이 코드를 작성합니다.

1
function print(person) {
2
if (person === undefined || person === null) {
3
console.log('person이 없네요')
4
return
5
}
6
console.log(person.name)
7
}
8
9
const person = null
10
print(person)

2.1 undefined와 null인 경우

위 코드는 다음과 같이 축약해서 작성 할 수 있습니다.

1
function print(person) {
2
// 1. undefined 와 null 은 Falsy 한 값
3
// 2. Falsy 한 값 앞에 느낌표를 붙여주면 true 로전환
4
if (!person) {
5
// <- 📝 person이 undefined나 null인 경우
6
console.log('person이 없네요')
7
return
8
}
9
console.log(person.name)
10
}
11
12
const person = null
13
print(person)

2.2 if문에서 Truthy 한 값 체크

Truthy 한 값과 Falsy 한 값은 if 문에서도 사용 가능

1
const value = { a: 1 }
2
3
// 1. value 가 Truthy 한 값이기 때문에, 콘솔에 메시지가 출력됨
4
// 2. 반면, value 가 null, undefined, 0, '', NaN 중 하나라면, 나타나지 않음
5
if (value) {
6
console.log('value 가 Truthy 하네요.')
7
}

3. short-circuit evaluation(단축평가 계산)

3.1 AND, OR 연산자

1
// 📝 AND(&&) 연산자
2
true && true // true
3
true && false // false
4
5
// 📝 OR(||) 연산자
6
true || false // true
7
false || true // true

3.2 if문에서 Truthy 한 값 체크

예를 들어, 다음과 같은 코드가 있다고 가정합니다.

1
const dog = {
2
name: '멍멍이',
3
}
4
5
function getName(animal) {
6
// 2. animal 객체가 undefined 이기 때문에
7
return animal.name // 3. undefined 에서 name 값을 조회 할 수 없어서 에러 발생😭
8
}
9
10
// 1. getName의 파라미터에 제대로된 객체가 주어지지 않으면?
11
const name = getName()
12
console.log(name)

함수에서 animal 값이 제대로 주어졌을 때만 name을 조회하고, 그렇지 않을때는 그냥 undefined를 반환하게 하고 싶으면?

1
function getName(animal) {
2
// animal 값이 제대로 주어졌을 때만 name을 조회
3
// animal 값이 없으면 undefined 반환
4
if (animal) {
5
return animal.name
6
}
7
return undefined
8
}

3.3 && 연산자로 코드 단축

1
const dog = {
2
name: '멍멍이',
3
}
4
5
function getName(animal) {
6
// animal 값이 제대로 주어졌을 때만 animal.name 반환
7
// animal 값이 없으면 undefined 반환
8
return animal && animal.name
9
}
10
11
const name = getName()
12
console.log(name) // undefined

추가 예시

1
console.log(true && 'hello') // hello
2
console.log(false && 'hello') // false
3
console.log('hello' && 'bye') // bye
4
console.log(null && 'hello') // null
5
console.log(undefined && 'hello') // undefined
6
console.log('' && 'hello') // ''
7
console.log(0 && 'hello') // 0
8
console.log(1 && 'hello') // hello
9
console.log(1 && 1) // 1

3.4 || 연산자로 코드 단축

만약 어떤 값이 Falsy 하다면 대체로 사용할 값을 지정해줄 때, 사용 가능

1
function getName(animal) {
2
const name = animal && animal.name
3
if (!name) {
4
return '이름이 없는 동물입니다'
5
}
6
return name
7
}

위 코드는 || 연산자를 사용하면 다음과 같이 단축시킬 수 있습니다.

1
function getName(animal) {
2
const name = animal && animal.name
3
4
// name이 falsy한값이라면, ||의 오른쪽의 값 출력
5
return name || '이름이 없는 동물입니다.'
6
}

4.. Conditional Rendering

보통 삼항연산자를 사용한 조건부 렌더링을 주로 특정 조건에 따라 보여줘야 하는 내용이 다를 때 사용합니다.

1
function Hello({ name, isSpecial }) {
2
// isSpecial이 false일땐 false이고, isSpecial이 true 일 땐 <b>*</b>
3
return (
4
<>
5
{isSpecial && <b>*</b>}
6
안녕하세요 {name}
7
</>
8
)
9
}

4.1 props 값 설정을 생략하면 =

컴포넌트의 props 값을 설정하게 될 때 만약 props 이름만 작성하고 값 설정을 생략한다면, 이를 true 로 설정한 것으로 간주함

1
function App() {
2
return (
3
<>
4
{/* isSpecial 이름만 넣어주면 isSpecial={true}와 동일한 의미 */}
5
<Hello name="react" color="red" isSpecial />
6
<Hello color="pink" />
7
</>
8
)
9
}