How to implement Conditional Rendering in React?
Last Updated :
02 Aug, 2024
This article explores JavaScript's conditional rendering in React JS, including various methods, syntax, and applications, leveraging React's virtual DOM, reusable components, props, and rapid rendering capabilities in single-page UI applications.
We will use the following approaches to implement conditional rendering in React
if-else statements:
if(condition){
expression1
}
else{
expression2
}
if-elseif statements:
if (condition) {
expression1
}
elseif(condition){
expression2
}
else {
expression3
}
'&&' operator:
condition && expression
A short-circuit logical AND is represented by the && operator. If this condition is satisfied, the following && expression shall be considered; if not, it shall be disregarded entirely. For simple conditional rendering, this approach is brief and widely used.
'&&' operator with the alternative operator '||':
condition && expression1 || expression2
If the condition is incorrect, a && operator and || can be combined to produce an alternate expression if there is a need for fallback expressions. This allows for different rendering scenarios to be handled more flexibly.
using ternary ( ?: ) operator:
condition ? expression1 : expression2
A more explicit way of expressing conditional rendering is provided by the ternary operator. In determining whether the condition is true or false, it will return a single expression.
Steps to Create the React App:
Step 1: Create a React project:
npx create-react-app conditional-rendering
Step 2: Navigate to the project:
cd conditional-rendering
Project Structure:
Project structure of the appThe updated dependencies in package.json file will look like:
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.2.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.1.3",
"react": "^18.1.0",
"react-dom": "^18.1.0",
"react-icons-kit": "^2.0.0",
"react-redux": "^8.0.2",
"react-scripts": "^5.0.1",
"redux": "^4.2.0",
"web-vitals": "^2.1.4"
}
Example: This example showcases a dynamic toggle switch controlled by the Dynamic App component, with UI updates based on state, and dynamic notifications indicating its status. Visual styles are managed through CSS classes, enabling modular reuse, and users can toggle the switch for immediate updates.
CSS
/* App.css */
.App {
font-family: sans-serif;
text-align: center;
}
body {
margin: 0;
padding: 0;
}
.toggle-slider {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.on {
background-color: aqua;
}
.off {
background-color: aliceblue;
}
button {
padding: 10px 15px;
border: none;
background-color: grey;
}
JavaScript
import React, { useState } from "react";
import "./App.css";
const DynamicApp = () => {
const [isToggled, setToggled] = useState(false);
const handleToggle =
() => {
setToggled(
(prevState) => !prevState);
};
return (
<div className={
`toggle-slider
${isToggled ? "on" : "off"}`
}>
<h1>Switch Application</h1>
<ToggleSwitch isToggled={isToggled}
onToggle={handleToggle} />
{isToggled ? (
<p>The color switch is ON!</p>
) : (
<p>The color switch is OFF!</p>
)}
</div>
);
};
const ToggleSwitch =
(
{
isToggled,
onToggle
}) => {
return (
<div
className={
`toggle-switch
${isToggled ? "on" : "off"}
`}
onClick={onToggle}>
<button>
{isToggled ? "Switch on" : "Switch off"}
</button>
</div>
);
};
export default DynamicApp;
Steps to run the app:
npm start
Output:
Example 2: This example features a basic React component showcasing hide-and-display functionality toggled by a button click. Utilizing the useState hook, it manages visibility state for dynamic UI updates.
CSS
/* Write CSS Here */
/* App.css */
.App {
font-family: sans-serif;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
min-height: 90vh;
}
button {
color: white;
background-color: black;
padding: 10px 20px;
}
JavaScript
import { useState } from "react";
export default function App() {
const [showText, setShowText] = useState(true);
const textVisibility = () => {
setShowText(!showText);
};
return (
<div className="App">
<center>
{!showText && (
<p>
GeeksforGeeks is a leading platform that provides
computer science resources and coding challenges for
programmers and technology enthusiasts, along with
interview and exam preparations for upcoming aspirants.
With a strong emphasis on enhancing coding skills and
knowledge, it has become a trusted destination for over
12 million plus registered users worldwide. The platform
offers a vast collection of tutorials, practice
problems, interview tutorials, articles, and courses,
covering various domains of computer science.
</p>
)}
<button onClick={textVisibility}>
{showText ? "Show some text" : "Hide it"}
</button>
</center>
</div>
);
}
Step to run the app:
npm start
Output:
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side : On client sid
11 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read