Conditional Rendering
Conditional rendering is a technique in React that allows you to render different components or elements based on certain conditions. This is particularly useful when you want to show or hide specific content depending on the state of your application.
In the example code above, we have a component called ConditionalRenderingExample
. It uses the useState
hook from React to manage a boolean state variable called isLoggedIn
. Based on the value of isLoggedIn
, we conditionally render either a welcome message or a login button.
When isLoggedIn
is true
, the component renders a heading element with the text 'Welcome, User!'. Otherwise, it renders a button element with the text 'Log In'.
By updating the value of isLoggedIn
using the setter function setIsLoggedIn
, we can toggle between the two states and see the corresponding content being rendered.
Conditional rendering is a powerful feature in React that allows you to dynamically show or hide content based on the state of your application. It can be used in various scenarios, such as displaying different UI components based on user authentication status, rendering components based on the results of an API call, or showing loading spinners while waiting for data to load.
In summary, conditional rendering in React enables you to render components conditionally based on certain conditions, enabling a more interactive and personalized user experience in your applications.
xxxxxxxxxx
import React, { useState } from 'react';
function ConditionalRenderingExample() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn ? (
<h1>Welcome, User!</h1>
) : (
<button onClick={() => setIsLoggedIn(true)}>Log In</button>
)}
</div>
);
}
export default ConditionalRenderingExample;