Conditional rendering in React allows you to create dynamic and interactive user interfaces by displaying different components or elements based on specific conditions. This chapter will cover everything from the basics of conditional rendering to advanced techniques, providing a comprehensive guide to mastering this essential concept. We will explore various methods for implementing conditional rendering, including if statements, ternary operators, logical AND operators, and more complex conditional structures.
Conditional rendering in React works the same way as conditions work in JavaScript. Different techniques can be used depending on the complexity and readability of your code.
You can use if statements to conditionally render a component or element.
import React from 'react';
function Greeting({ isLoggedIn }) {
if (isLoggedIn) {
return Welcome back!
;
} else {
return Please sign in.
;
}
}
export default Greeting;
Greeting
component receives a prop isLoggedIn
.isLoggedIn
and returns different elements accordingly.
Welcome back!
Please sign in.
Ternary operators provide a concise way to handle simple conditional rendering.
import React from 'react';
function Greeting({ isLoggedIn }) {
return (
{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}
);
}
export default Greeting;
isLoggedIn
and returns one of two possible values.
Welcome back!
Please sign in.
For conditions where you only need to render something when a condition is true, you can use the logical AND operator.
import React from 'react';
function Mailbox({ unreadMessages }) {
return (
Hello!
{unreadMessages.length > 0 && (
You have {unreadMessages.length} unread messages.
)}
);
}
export default Mailbox;
&&
renders the message only if unreadMessages.length
is greater than 0.
Hello!
You have [number] unread messages.
Inline if-else with the conditional operator (ternary) is useful for rendering one of two components or elements based on a condition.
import React from 'react';
function UserStatus({ isOnline }) {
return (
{isOnline ? (
Online
) : (
Offline
)}
);
}
export default UserStatus;
span
with class online
or span
with class offline
based on isOnline
.
Online
Offline
You can also use variables to store elements or components before including them in the return statement.
import React from 'react';
function LoginControl({ isLoggedIn }) {
let button;
if (isLoggedIn) {
button = ;
} else {
button = ;
}
return (
Login Control
{button}
);
}
export default LoginControl;
button
variable stores the appropriate button element based on isLoggedIn
.
Login Control
Sometimes you may want to prevent a component from rendering at all.
import React from 'react';
function WarningBanner({ warn }) {
if (!warn) {
return null;
}
return (
Warning!
);
}
function Page() {
const [showWarning, setShowWarning] = React.useState(true);
const toggleWarning = () => {
setShowWarning(!showWarning);
};
return (
);
}
export default Page;
WarningBanner
component returns null
if warn
is false
, preventing it from rendering.Page
component toggles the showWarning
state, showing or hiding the WarningBanner
.
Warning!
You can conditionally render elements within lists.
import React from 'react';
function TodoList({ todos }) {
return (
{todos.map((todo, index) =>
todo.completed ? null : - {todo.text}
)}
);
}
export default TodoList;
TodoList
component maps over the todos
array.li
element for each todo that is not completed.
- [todo.text]
You can render different components based on multiple conditions.
import React from 'react';
function AdminPanel() {
return Admin Panel
;
}
function UserPanel() {
return User Panel
;
}
function Panel({ isAdmin }) {
return (
{isAdmin ? : }
);
}
export default Panel;
Panel
component conditionally renders either AdminPanel
or UserPanel
based on isAdmin
.
Admin Panel
User Panel
For more complex conditions, you can use switch cases.
import React from 'react';
function Status({ status }) {
let message;
switch (status) {
case 'loading':
message = Loading...
;
break;
case 'success':
message = Data Loaded Successfully!
;
break;
case 'error':
message = Error Loading Data!
;
break;
default:
message = Unknown Status
;
}
return (
{message}
);
}
export default Status;
Status
component uses a switch statement to determine which message to display based on status
.
Loading...
Data Loaded Successfully!
Error Loading Data!
Unknown Status
In this example, we will create a simple application that conditionally renders content based on whether a user is logged in or not. We will have a login button, a logout button, and a message that changes based on the user’s authentication status.
import React, { useState } from 'react';
import Greeting from './Greeting';
import AuthButton from './AuthButton';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const handleLogin = () => {
setIsLoggedIn(true);
};
const handleLogout = () => {
setIsLoggedIn(false);
};
return (
);
}
export default App;
import React from 'react';
function Greeting({ isLoggedIn }) {
return (
{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}
);
}
export default Greeting;
import React from 'react';
function AuthButton({ isLoggedIn, onLogin, onLogout }) {
return (
);
}
export default AuthButton;
App
component maintains the state isLoggedIn
to track the user’s authentication status.Greeting
component displays a message based on whether the user is logged in or not.AuthButton
component renders a login button if the user is not logged in and a logout button if the user is logged in. It also handles the login and logout actions by calling the appropriate functions passed as props.
Please sign in.
Welcome back!
Please sign in.
In this example, we will create an application that shows or hides additional information based on a toggle button. This will demonstrate more complex conditional rendering by controlling the visibility of a component.
import React, { useState } from 'react';
import InfoToggle from './InfoToggle';
function App() {
const [showInfo, setShowInfo] = useState(false);
const toggleInfo = () => {
setShowInfo(!showInfo);
};
return (
Conditional Rendering Example
{showInfo && }
);
}
export default App;
import React from 'react';
function InfoToggle() {
return (
Additional Information
This is some extra information that can be shown or hidden by clicking the button above.
);
}
export default InfoToggle;
App
component maintains the state showInfo
to determine whether the InfoToggle
component should be displayed.InfoToggle
component contains the additional information that can be toggled.App
component toggles the showInfo
state, which in turn controls the rendering of the InfoToggle
component.
Conditional Rendering Example
Conditional Rendering Example
Additional Information
This is some extra information that can be shown or hidden by clicking the button above.
Conditional Rendering Example
Conditional rendering is a powerful feature in React that allows you to create dynamic and interactive user interfaces. By understanding and utilizing different conditional rendering techniques, such as if statements, ternary operators, logical AND operators, and switch cases, you can effectively manage the display of components and elements based on various conditions. Happy coding !❤️