React Conditionals
React provides various ways to handle conditional rendering, allowing you to render different components or elements based on specific conditions. Conditional rendering is fundamental in React applications to display dynamic content based on user interactions, state changes, or props.
1. Using if-else Statement
We can use a standard JavaScript If Else statement to conditionally render JSX content.
The syntax of if-else statement is:
if(expression/condition){
// statements
} else{
// statements
}
If expression or condition is true
, then the statements inside if
block execute. If the condition is false, then the statements inside else
block execute
Example: Dynamic Message based on Login Status
In the following example, we use a standard JavaScript if
statement to conditionally render a message based on the user’s login status. The component checks the value of a isLoggedIn
state and renders a greeting or a login prompt accordingly.
App.js
import React, { useState } from 'react';
function LoginStatus() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const handleLogin = () => {
setIsLoggedIn(true);
};
const handleLogout = () => {
setIsLoggedIn(false);
};
let message;
if (isLoggedIn) {
message = <p>Welcome back, user!</p>;
} else {
message = <p>Please log in.</p>;
}
return (
<div>
{message}
<button onClick={isLoggedIn ? handleLogout : handleLogin}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
</div>
);
}
export default LoginStatus;
Explanation:
if
Statement: Checks theisLoggedIn
state to determine which message to display.- Dynamic Button: The button text and action are based on the current login status.
- This approach is straightforward and suitable for simple conditions.
Output:
2. Using Ternary Operator
We can also use a JavaScript Ternary Operator to conditionally render JSX content.
The syntax of Ternary Operator is:
condition? value1 : value2
If condition evaluates to true, then value1 is returned, else, value2 is returned.
Example: Dynamic Message based on Login Status
This example demonstrates how to use the ternary operator for inline conditional rendering. We will render a greeting or a prompt based on the user’s login status directly within the JSX.
import React, { useState } from 'react';
function Greeting() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn ? <p>Hello, User!</p> : <p>Please log in to continue.</p>}
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? 'Log Out' : 'Log In'}
</button>
</div>
);
}
export default Greeting;
Explanation:
- Ternary Operator: Simplifies conditional rendering directly within the JSX.
- Clean Syntax: Conditionally renders either the greeting or login prompt in one line.
- This approach is concise and ideal for simple conditions embedded in JSX.
Output:
3. Using Logical AND (&&
) Operator
In this example, we conditionally display a message using the logical AND (&&
) operator. This approach is useful when you only want to render something if a specific condition is true.
import React, { useState } from 'react';
function ConditionalMessage() {
const [showMessage, setShowMessage] = useState(false);
return (
<div>
<button onClick={() => setShowMessage(!showMessage)}>
{showMessage ? 'Hide Message' : 'Show Message'}
</button>
{showMessage && <p>This is a conditional message!</p>}
</div>
);
}
export default ConditionalMessage;
Explanation:
- Logical AND Operator: Renders the message only when
showMessage
is true. - Button Toggles State: Clicking the button updates the
showMessage
state. - This approach is concise and effective for rendering content conditionally based on a single condition.
Output:
4. Using switch
Statement
We can also use a JavaScript Switch statement to conditionally render JSX content.
The syntax of Switch statement is:
switch(expression){
case value_1 :
// statements
break;
case value_2 :
// statements
break;
default :
// statements
}
The switch expression is evaluated and each case value is matched against it. When there is a match for a case value, the corresponding block of statements are executed.
Example: Conditional Rendering using Switch Statement
Here, we use a switch
statement to render different messages based on a user role. This approach is helpful when there are multiple conditions to handle.
import React, { useState } from 'react';
function UserRole() {
const [role, setRole] = useState('guest');
let message;
switch (role) {
case 'admin':
message = <p>Welcome, Admin!</p>;
break;
case 'user':
message = <p>Welcome, User!</p>;
break;
default:
message = <p>Welcome, Guest!</p>;
}
return (
<div>
{message}
<button onClick={() => setRole('guest')}>Guest</button>
<button onClick={() => setRole('user')}>User</button>
<button onClick={() => setRole('admin')}>Admin</button>
</div>
);
}
export default UserRole;
Explanation:
switch
Statement: Evaluates therole
state and renders the corresponding message.- Buttons Update Role: Clicking a button updates the
role
state toguest
,user
, oradmin
. - This approach is scalable and clean for handling multiple conditions.
Output:
Conclusion
Conditional rendering in React allows you to build dynamic and interactive user interfaces. Depending on the complexity of your conditions, you can use if
statements, ternary operators, logical AND, or switch
statements to display content effectively. Start experimenting with these approaches to master conditional rendering in React!