In React, you can use JavaScript's conditional operators (like if, else, ternary operator, etc.) to control what should be displayed.
Conditional rendering in React allows you to render different UI components or elements based on certain conditions. It is similar to "if-else" statements in JavaScript but for deciding what to display on the screen.
Example 1: Using if-else condition
export function WelcomeMessage(props) {
const isLoggedIn = props.loggedIn;
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please sign in.</h1>;
}
}
If isLoggedIn is true, the message "Welcome back!" is shown. If isLoggedIn is false, the message "Please sign in." is shown.
Example 2: Using ternary operator.
export function WelcomeMessageUsingTernary(props) {
return props.loggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>;
}
Example 3: Using logical && operator.
{isLoggedIn && <p>You have new notifications!</p>}
The message ‘You have new notifications!’ is shown only when isLoggedIn evaluate to true.
export function GreetUser(props) {
const isLoggedIn = props.loggedIn;
return (
<div>
{isLoggedIn ? <h1>Hello, User!</h1> : <h1>Please log in.</h1>}
{isLoggedIn && <p>You have new notifications!</p>}
</div>
);
}
Follow below step-by-step procedure to build the complete working application.
Step 1: Go to the post (Quickly Set Up a React Project with Vite: A Step-by-Step), and set up a React Project ‘conditional_rendering’
npm create vite@latest
Project structure looks like below.
Step 2: Create components folder in src/ folder and define WelcomeMessage component.
WelcomeMessage.jsx
export function WelcomeMessage(props) {
const isLoggedIn = props.loggedIn;
if (isLoggedIn) {
return <h1>Welcome back!</h1>;
} else {
return <h1>Please sign in.</h1>;
}
}
export function WelcomeMessageUsingTernary(props) {
return props.loggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>;
}
export function GreetUser(props) {
const isLoggedIn = props.loggedIn;
return (
<div>
{isLoggedIn ? <h1>Hello, User!</h1> : <h1>Please log in.</h1>}
{isLoggedIn && <p>You have new notifications!</p>}
</div>
);
}
Step 3: Update main.jsx like below.
main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import {WelcomeMessage, WelcomeMessageUsingTernary, GreetUser} from './components/WelcomeMessage'
createRoot(document.getElementById('root')).render(
<StrictMode>
<WelcomeMessage loggedIn={true} />
<WelcomeMessageUsingTernary loggedIn={true} />
<GreetUser loggedIn={true} />
</StrictMode>,
)
Step 4: Build and run the Application.
cd conditional_rendering npm install npm run dev
Open the url ‘http://localhost:5173/’ in browser, you can see below screen.
You can download the application from this link.
Previous Next Home
No comments:
Post a Comment