조건부 렌더링
조건 별 처리
JavaScript 프로그래밍에서 조건 처리는 일반적으로 if, switch 문과 함께 사용합니다. JSX 또한 JavaScript 객체이므로 JavaScript 프로그래밍이 가능합니다. 아래 예시는 함수 실행 과정에 전달된 매개변수의 조건의 참, 거짓 유무에 따라 반환되는 React 요소가 달라집니다.
function conditionalRendering(content, isStrong = false) {
if (isStrong) {
return <strong>{content}</strong>
} else {
return <p>{content}</p>
}
}
// <p>조건부 렌더링</p>
const normalMessage = conditionalRendering('조건부 렌더링')
// <strong>조건부 렌더링</strong>
const strongMessage = conditionalRendering('조건부 렌더링', true)const switchRendering = (emotion) => {
switch (emotion) {
default:
case '좋아요':
return getEmotionFace('good.jpg', emotion)
case '훈훈해요':
return getEmotionFace('so-good.jpg', emotion)
case '슬퍼요':
return getEmotionFace('sad.jpg', emotion)
case '화나요':
return getEmotionFace('angry.jpg', emotion)
case '후속기사원해요':
return getEmotionFace('want.jpg', emotion)
}
}
switchRendering('후속기사원해요')라이브 예제
인라인 조건 처리
조건 처리는 React 요소의 속성에서도 사용할 수 있습니다. 예를 들어 3항 식을 사용해 JSX 안에서 조건 처리 하거나,
<abbr title={abbrs.jsx ? abbrs.jsx : null}>{headline}</abbr>논리 곱(&&, AND) / 합(||, OR) 연산자를 사용한 조건 처리도 가능합니다.
<abbr title={abbrs.jsx || null}>{headline}</abbr>또는 함수를 활용해 조건 처리된 값을 JSX 안에 설정해 처리할 수 있습니다. 함수는 값을 반환하니까요.
function findAbbr(key) {
if (key in abbrs) {
return abbrs[key]
} else {
return null
}
}
const abbr = <abbr title={findAbbr('jsx')}>{headline}</abbr>JavaScript 식과 함수는 값을 반환하기에 JSX 코드에서 사용할 수 있지만, 문은 값을 반환하지 않으므로 JSX 코드에서 사용할 수 없습니다. (if, switch, for, while 문 등)
Vue의 조건부 렌더링
Vue와 Angular는 템플릿 엔진을 사용하고, 디렉티브(Directives)를 사용해 조건부 렌더링 합니다.
<div id="conditional-rendering">
<span v-if="seen">이제 나를 볼수 있어요</span>
</div>Last updated
Was this helpful?