Front-end/React
조건부로 여러 요소 렌더링하기
mooyou
2025. 1. 6. 18:01
728x90
300x250
SMALL
React Fragment를 사용해 조건에 따라 여러 요소를 렌더링할 수 있다.
function Example({ isAdmin, isUser }) {
return (
<div>
{isAdmin && (
<>
<h1>Admin Panel</h1>
<p>You have full access.</p>
</>
)}
{isUser && !isAdmin && (
<>
<h1>User Dashboard</h1>
<p>Welcome to your dashboard.</p>
</>
)}
{!isAdmin && !isUser && (
<>
<h1>Guest Access</h1>
<p>Please log in to see more content.</p>
</>
)}
</div>
);
}
- isAdmin이 true인 경우 : 관리자 패널 요소 렌더링
- isUser만 true인 경우 : 사용자 대시보드 렌더링
- 둘 다 false인 경우 : 게스트 접근 화면 렌더링
if문을 사용한 예시
만약 조건이 복잡하거나 여러 가지 상태를 처리해야 할 경우에는 if 문이나 switch문이 더 적합할 수 있다.
function Example({ userType }) {
if (userType === "admin") {
return (
<div>
<h1>Admin Panel</h1>
<p>You have full access.</p>
</div>
);
} else if (userType === "user") {
return (
<div>
<h1>User Dashboard</h1>
<p>Welcome to your dashboard.</p>
</div>
);
} else {
return (
<div>
<h1>Guest Access</h1>
<p>Please log in to see more content.</p>
</div>
);
}
}
728x90
반응형
LIST