조건부 렌더링(Conditional Rendering)
특정 조건에 따라 컴포넌트나 요소를 화면에 보여줄지 여부를 결정하는 방식
JavaScript의 조건문을 사용하여 구현되며,
조건에 맞으면(if) 해당 컴포넌트나 요소를 렌더링하고,
그렇지 않으면(else if / else) 다른 컴포넌트나 요소를 렌더링하거나 아무것도 렌더링하지 않을 수 있다.
조건부 렌더링을 구현하는 방법
- if 문: 전통적인 if 문을 사용하여 조건에 맞는 컴포넌트를 반환할 수 있습니다.
- 삼항 연산자 (? :): 간단한 조건부 렌더링을 위해 많이 사용됩니다.
- && 연산자: 조건이 참일 때만 컴포넌트를 렌더링합니다.
- switch 문: 여러 조건을 처리해야 할 때 사용할 수 있습니다.
▶ if 문을 사용한 조건부 렌더링
// Greeting.jsx (컴포넌트)
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
// 조건부 렌더링(if문)
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please sign up.</h1>;
}
}
// App.jsx
function App() {
return (
<div>
<Greeting isLoggedIn={true} />
</div>
);
}
isLoggedIn이라는 prop에 따라 다른 텍스트가 렌더링
▶ 삼항 연산자를 사용한 조건부 렌더링
// Greeting.jsx(컴포넌트)
function Greeting(props) {
return (
// 삼항연산자
<h1>{props.isLoggedIn ? 'Welcome back!' : 'Please sign up.'}</h1>
);
}
// App.jsx
function App() {
return (
<div>
<Greeting isLoggedIn={false} />
</div>
);
}
if문과 비교할 때, 더 간결해진 점을 볼 수 있다.
▶ && 연산자를 사용한 조건부 렌더링
// UserGreeting.jsx(컴포넌트)
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
// GuestGreeting.jsx(컴포넌트)
function GuestGreeting(props) {
return <h1>Please sign up.</h1>;
}
// Greeting.jsx(컴포넌트)
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
return (
<div>
<h1>Hello, User!</h1>
// 조건부 렌더링(&&)
{isLoggedIn && <UserGreeting />}
</div>
);
}
// App.jsx
function App() {
return (
<div>
<Greeting isLoggedIn={true} />
</div>
);
}
isLoggedIn && <UserGreeting /> : isLoggedIn이 true일 때만 <UserGreeting /> 컴포넌트가 렌더링
false일 시 랜더링이 되지 않는다.
따라서 true면 UserGreeting에 있는 h1태그 형식의 Welcome back! 이 화면에 출력
false인 경우 빈 공간으로 출력된다.
&& 연산자를 사용한 조건부 렌더링은 특정 조건이 참일 때만 JSX 요소를 렌더링할 때 유용하다.
▶ switch 문을 사용한 조건부 렌더링
// Greeting.jsx
function Greeting(props) {
const { userRole } = props;
// switch문을 이용한 조건부 렌더링
switch (userRole) {
case 'admin':
return <h1>Welcome, Admin!</h1>;
case 'editor':
return <h1>Welcome, Editor!</h1>;
case 'viewer':
return <h1>Welcome, Viewer!</h1>;
default:
return <h1>Welcome, Guest!</h1>;
}
}
// App.jsx
function App() {
return (
<div>
{/* userRole 값을 admin, editor, viewer 또는 undefined로 변경해서 테스트 */}
<Greeting userRole="editor" />
</div>
);
}
userRole="editor" → Welcome, Editer! 출력
userRole="admin" → Welcome, Admin! 출력
userRole="viewer" → Welcome, Viewer! 출력
그 외 Welcome, Guest! 출력
여러 조건을 명확하게 구분하고 관리할 수 있어 복잡한 조건을 처리할 때 유리하다.
'React' 카테고리의 다른 글
| React에서 CSS 적용하는 다양한 방법 (0) | 2024.10.14 |
|---|---|
| 리스트 렌더링 filter() & map() (0) | 2024.10.11 |
| 상태관리 State (0) | 2024.10.07 |
| Prop[properties : 속성] (0) | 2024.10.04 |
| JSX & Component (0) | 2024.10.02 |