How to conditionally render components in ReactJS ?
Last Updated :
29 Jul, 2024
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook.
Prerequisites
Conditional Rendering
To create multiple components and render them based on some conditions. This is also a kind of encapsulation supported by React. When UI is designed using React, we come across a situation when components are to be rendered on the screen based on some condition. For eg, In a University Information System, when a teacher login, different components are rendered whereas when a student login, different components are rendered. This is called the Conditional Rendering of React Components.
Syntax:
{statement} ? true : false
How to do Conditional Rendering?
It is done using stateVariable. The value of the stateVariable determines whether to render the component or not. Its value can be changed by the occurrence of any event like onClick.
Steps to Create the React Application And Installing Module
Step 1: Create a react application using the following command.
npx create-react-app foldername
Step 2: Once it is done, change your directory to the newly created application using the following command.
cd foldername
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-router-dom": "^6.25.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Example:
- In below example we have created two components Login.js and Dashboard.js in the components folder.
- In Login.js components we will implement a form with fields for username and password and handle form submission and simulate login.
- In Dashboard.js we will display a welcome message and a logout button.
- In App.j component we use React state to track if a user is logged in.
- Then in App.js we will conditionally render either Login or Dashboard based on the login state.
JavaScript
// App.js
import React, { useState } from 'react';
import Login from './components/Login';
import Dashboard from './components/Dashboard';
import './App.css';
const App = () => {
const [user, setUser] = useState(null);
const handleLogin = (user) => {
setUser(user);
};
const handleLogout = () => {
setUser(null);
};
return (
<div className="app-container">
{user ? (
<Dashboard user={user} onLogout={handleLogout} />
) : (
<Login onLogin={handleLogin} />
)} </div>
);
};
export default App;
JavaScript
// Login.js
import React, { useState } from 'react';
const Login = ({ onLogin }) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
// Simulate login process
if (username === 'user' && password === 'password') {
onLogin({ name: username });
} else {
alert('Invalid credentials');
}
};
return (
<div className="login-container">
<h2>Login</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div>
<label>Password:</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit">Login</button>
</form>
</div>
);
};
export default Login;
JavaScript
// Dashboard.js
import React from 'react';
const Dashboard = ({ user, onLogout }) => {
return (
<div className="dashboard-container">
<h2>Welcome, {user.name}</h2>
<button onClick={onLogout}>Logout</button>
</div>
);
};
export default Dashboard;
Step to Run the application: Run your app by executing the below command in the src
npm start
Output:
Conditional Rendering
Similar Reads
Conditional rendering component using Enums in ReactJS In certain scenarios, a ReactJS developer may have to dynamically display or hide components depending on specific conditions. For instance, when creating a To-Do list application, the developer must render tasks if there are pending items; otherwise, they should display a message such as "No pendin
3 min read
How to create components in ReactJS ? Components in React JS is are the core of building React applications. Components are the building blocks that contains UI elements and logic, making the development process easier and reusable. In this article we will see how we can create components in React JS. Table of Content React Functional C
3 min read
How To Conditionally Add Attributes To React Components? In React, it's common to render components based on certain conditions dynamically. Often, you may need to add or remove attributes to a React component based on the application's state, the props passed down, or other factors. Handling these dynamic conditions effectively is key to building flexibl
3 min read
How to create a Read More component in ReactJS? Creating a Read More component in React JS refers to hiding and displaying the text content on the page. It can be achieved by setting the state variable and display the content accordingly. PrerequisitesNode.JS and npmReact JSReact JS useState() hookApproachTo create a Read More component in React
3 min read
How to implement Conditional Rendering in React? 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 con
4 min read