Conditional rendering in React refers to the ability to render different content or components based on certain conditions. This allows you to dynamically show or hide parts of your UI based on user interactions, data fetched from an API, or any other condition.
Here's an example demonstrating conditional rendering:
import React, { useState } from 'react';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
// Function to handle login
const handleLogin = () => {
setIsLoggedIn(true);
};
// Function to handle logout
const handleLogout = () => {
setIsLoggedIn(false);
};
return (
<div>
{isLoggedIn ? (
<div>
<h1>Welcome, User!</h1>
<button onClick={handleLogout}>Logout</button>
</div>
) : (
<div>
<h1>Please log in</h1>
<button onClick={handleLogin}>Login</button>
</div>
)}
</div>
);
}
export default App;
In this example:
- We have a state variable
isLoggedIn
initialized to false using theuseState
hook. - We have two functions:
handleLogin
andhandleLogout
, which respectively update theisLoggedIn
state to true or false. - The
isLoggedIn
state variable is used to conditionally render different content. - If isLoggedIn is
true
, it renders a welcome message and alogout
button. If isLoggedIn isfalse
, itrenders
alogin
prompt
and alogin button
. - Depending on the value of
isLoggedIn
, different JSX elements are rendered.
This is just a basic example, and conditional rendering can become more complex depending on the specific requirements of your application. You can use any JavaScript expressions within curly braces {}
to determine the conditions for rendering.
Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js
Top comments (0)