Currently When I am logged in or out my content is hidden. I want my content to show when logged in, but hidden when logged out. I want to write a ternary and to set a token that is either true or false to determine if a user will see or will not see my content.
If someone could show me in a clear and simple way how to solve this issue it would be great. How can I render either true or false here based off of whether a user is logged in or not?
CodePudding user response:
Here's a simple example of how to display content according to a state :
import React, { useState } from 'react';
function MyComponent() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
{isLoggedIn ? <div>Content that is visible when logged in</div> : null}
</div>
);
}
export default MyComponent;
CodePudding user response:
If login operation is successful when you log in for the user, save the access token to localstorage.
const user = localStorage.setItem('token', res.data.access);
then where you need to check
if(localStorage.getItem('token') !== undefined) { --the part you want to hide }
NOTE: If there are other user data you get from JWT. (user_name, user_id, image, permission.. ) this is not the best practice. If your project is big and you need information as I mentioned above. You must first decode the JWT and then create the localstorageta user.