- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React Conditional Rendering
- Conditional rendering in React involves displaying different components or content based on certain conditions.
- It allows you to create dynamic and responsive user interfaces.
Using the Ternary Operator
The ternary operator is a concise way to conditionally render content.
import React, { useState } from 'react';
const ConditionalRendering = () => {
const [isLoggedIn, setIsLoggedIn] = useState(true);
return (
<div>
{isLoggedIn ? (
<p>Welcome, User!</p>
) : (
<p>Please log in</p>
)}
</div>
);
};
Using Logical && Operator
The && operator can be used for simple conditional rendering.
import React, { useState } from 'react';
const ConditionalRenderingLogical = () => {
const [showMessage, setShowMessage] = useState(true);
return (
<div>
{showMessage && <p>This message is shown conditionally.</p>}
</div>
);
};
Using if Statements
While you can't use if statements directly in JSX, you can use them in the surrounding JavaScript code.
import React, { useState } from 'react';
const ConditionalRenderingIfStatement = () => {
const [isSpecial, setIsSpecial] = useState(true);
let content;
if (isSpecial) {
content = <p>This is a special message!</p>;
} else {
content = <p>This is a regular message.</p>;
}
return <div>{content}</div>;
};
Switch Statement for Multiple Conditions
A switch statement can be used for more complex conditional rendering.
import React, { useState } from 'react';
const ConditionalRenderingSwitch = () => {
const [userRole, setUserRole] = useState('admin');
let content;
switch (userRole) {
case 'admin':
content = <p>Welcome, Admin!</p>;
break;
case 'user':
content = <p>Hello, User!</p>;
break;
default:
content = <p>Unknown Role</p>;
}
return <div>{content}</div>;
};
Summary
Understanding and using conditional rendering in React is essential for creating dynamic and user-friendly interfaces. Whether it's a simple ternary operator or a more complex switch statement, the ability to conditionally render content greatly enhances the flexibility of your React components.