Conditional rendering in React allows components to render different UI elements based on certain conditions. It is a powerful feature that lets you display or hide content, change the appearance of elements, or even render entire components based on conditions like state, props, or user input.
1. Basic Concept of Conditional Rendering
In React, you can use JavaScript expressions within JSX to conditionally render content. Since JSX is essentially JavaScript, it can accept expressions inside curly braces {}. You can use basic JavaScript control structures, such as if, else, ternary operators, and logical && (AND) operators, to determine what to render.
2. Using if Statements
In React, you cannot directly use if statements inside JSX. However, you can handle conditional logic before the return statement in your component’s render method (for class components) or the functional component’s body.
Example of Conditional Rendering Using if in a Class Component:
import React, { Component } from 'react';
class Greeting extends Component {
constructor(props) {
super(props);
this.state = { isLoggedIn: true };
}
render() {
const { isLoggedIn } = this.state;
let greetingMessage;
if (isLoggedIn) {
greetingMessage = <h1>Welcome back!</h1>;
} else {
greetingMessage = <h1>Please sign up.</h1>;
}
return <div>{greetingMessage}</div>;
}
}
export default Greeting;
In this example:
- The
Greetingcomponent decides whether to show a “Welcome back!” or “Please sign up.” message based on theisLoggedInstate. - The
ifstatement is used to assign the message to a variable before rendering.
Example Using if in a Functional Component:
import React, { useState } from 'react';
function Greeting() {
const [isLoggedIn, setIsLoggedIn] = useState(true);
let greetingMessage;
if (isLoggedIn) {
greetingMessage = <h1>Welcome back!</h1>;
} else {
greetingMessage = <h1>Please sign up.</h1>;
}
return <div>{greetingMessage}</div>;
}
export default Greeting;
3. Using Ternary Operator
The ternary operator is a shorthand way to express conditional logic. It’s often used in JSX because it’s concise and readable.
Example Using Ternary Operator:
import React, { useState } from 'react';
function Greeting() {
const [isLoggedIn, setIsLoggedIn] = useState(true);
return (
<div>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
</div>
);
}
export default Greeting;
In this example:
- The ternary operator checks the
isLoggedInstate. - It renders either “Welcome back!” if
isLoggedInistrueor “Please sign up.” ifisLoggedInisfalse.
4. Using Logical && (AND) Operator
The && operator is often used for conditional rendering when you want to render something only when a certain condition is true. If the condition is false, nothing is rendered.
Example Using && Operator:
import React, { useState } from 'react';
function Greeting() {
const [isLoggedIn, setIsLoggedIn] = useState(true);
return (
<div>
{isLoggedIn && <h1>Welcome back!</h1>}
{!isLoggedIn && <h1>Please sign up.</h1>}
</div>
);
}
export default Greeting;
In this example:
- The first
h1element is rendered only whenisLoggedInistrue. - The second
h1element is rendered whenisLoggedInisfalse.
5. Rendering Elements Conditionally Based on User Interaction
You can also conditionally render UI based on user interactions, like clicking a button or submitting a form. The state or props can change based on user actions, triggering a re-render with different content.
Example of Conditional Rendering with Button Click:
import React, { useState } from 'react';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
</div>
);
}
export default App;
In this example:
- The
buttontext toggles between “Log In” and “Log Out” based on whether the user is logged in or not. - When the user clicks the button, the
isLoggedInstate toggles, and the greeting message is conditionally rendered.
6. Conditional Rendering of Entire Components
Sometimes, you may want to conditionally render entire components based on certain conditions. This is especially useful for showing or hiding entire sections of a page or switching between different views.
Example of Conditional Rendering of Entire Components:
import React, { useState } from 'react';
function Login() {
return <h2>Please log in to continue.</h2>;
}
function Dashboard() {
return <h2>Welcome to your dashboard!</h2>;
}
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
{isLoggedIn ? <Dashboard /> : <Login />}
</div>
);
}
export default App;
In this example:
- The
Logincomponent is rendered when the user is not logged in, and theDashboardcomponent is shown when the user is logged in. - This allows for the conditional rendering of entire components based on state.
7. Inline Conditional Rendering with Logical Operators
You can also perform inline conditional rendering within JSX to make the UI rendering decisions based on expressions.
Example with Inline Conditional Rendering:
import React, { useState } from 'react';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
{isLoggedIn && <h1>Welcome to your dashboard!</h1>}
{!isLoggedIn && <h1>Please log in first.</h1>}
</div>
);
}
export default App;
8. Summary of Conditional Rendering Techniques
| Method | Example | Use Case |
|---|---|---|
if Statement | Used before the return statement for complex logic. | When you have multiple conditions or more complex logic. |
| Ternary Operator | {condition ? <ComponentA /> : <ComponentB />} | For simple true/false conditions in JSX. |
Logical && (AND) Operator | {condition && <Component />} | For rendering something when a condition is true. |
| User Interaction | Using buttons or inputs to toggle rendering based on user actions. | Dynamic changes in UI based on user interactions. |
| Rendering Entire Components Conditionally | {condition ? <ComponentA /> : <ComponentB />} | When switching between views or components. |
