import React, { useState } from 'react';
function Example() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
function handleLogin() {
setIsLoggedIn(true);
}
function handleLogout() {
setIsLoggedIn(false);
}
return (
<div>
{isLoggedIn ? (
<div>
<p>Welcome, you are logged in.</p>
<button onClick={handleLogout}>Logout</button>
</div>
) : (
<div>
<p>Please log in to continue.</p>
<button onClick={handleLogin}>Login</button>
</div>
)}
</div>
);
}
In this example, the isLoggedIn
state variable is used to determine whether to render the "Logged in" or "Please log in" message, as well as the corresponding login or logout button. When the user clicks the login or logout button, the handleLogin
or handleLogout
function is called, which updates the isLoggedIn
state variable and triggers a re-render of the component with the updated content.