Rendering Components Conditionally
In React, you can render components conditionally based on certain conditions or states. This allows you to show different components or content depending on the current state of your application.
For example, let's say you have a simple application where a user can either be logged in or be a guest. You want to display a personalized greeting if the user is logged in, and a signup prompt if the user is a guest.
Here's an example of how you can conditionally render components based on the value of a prop:
1function UserGreeting() {
2 return (
3 <div>
4 <h1>Welcome back!</h1>
5 <button onClick={logout}>Logout</button>
6 </div>
7 );
8}
9
10function GuestGreeting() {
11 return (
12 <div>
13 <h1>Please sign up.</h1>
14 <button onClick={login}>Login</button>
15 </div>
16 );
17}
18
19function Greeting(props) {
20 const isLoggedIn = props.isLoggedIn;
21
22 if (isLoggedIn) {
23 return <UserGreeting />;
24 }
25 return <GuestGreeting />;
26}
27
28function App() {
29 const [isLoggedIn, setIsLoggedIn] = useState(false);
30
31 const login = () => {
32 setIsLoggedIn(true);
33 };
34
35 const logout = () => {
36 setIsLoggedIn(false);
37 };
38
39 return (
40 <div>
41 <Greeting isLoggedIn={isLoggedIn} />
42 </div>
43 );
44}
45
46ReactDOM.render(
47 <React.StrictMode>
48 <App />
49 </React.StrictMode>,
50 document.getElementById('root')
51);
In this example, we have three components: UserGreeting
, GuestGreeting
, and Greeting
.
UserGreeting
component displays a welcome message and a button to logout.GuestGreeting
component displays a signup prompt and a button to login.Greeting
component checks theisLoggedIn
prop and renders either theUserGreeting
orGuestGreeting
component accordingly.
The parent App
component holds the isLoggedIn
state and passes it to the Greeting
component as a prop.
When the login
button is clicked, the isLoggedIn
state is set to true
, and the UserGreeting
component is rendered.
When the logout
button is clicked, the isLoggedIn
state is set to false
, and the GuestGreeting
component is rendered.
By rendering components conditionally, you can provide a personalized user experience based on the current state or conditions of your application.
xxxxxxxxxx
);
// Let's create a simple example
function UserGreeting() {
return (
<div>
<h1>Welcome back!</h1>
<button onClick={logout}>Logout</button>
</div>
);
}
function GuestGreeting() {
return (
<div>
<h1>Please sign up.</h1>
<button onClick={login}>Login</button>
</div>
);
}
// Create a component that determines whether
// to render UserGreeting or GuestGreeting based on
// the value of the isLoggedIn prop.
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;