I am trying to create a logoff button in react, and although it works (logs the user out) I want to make the button hidden unless my localstorage has a value for 'token'. At this point when it is not null, I would like my logoff button to then appear on screen for a user to logoff.
The section where I call this button is below, which currently only has an onclick event if my localstorage has a value assigned to 'token'
import React from "react"; import { render } from "react-dom"; import Login from "./Login"; import Register from "./Register"; import Logout from "./logout"; import Button from "react-bootstrap/Button"; render( <> <Login /> <div> <h1>OR</h1> </div> <Register /> </div> <Button onClick={event => {if(localStorage.getItem('token') !== null) Logout()}} }>Logout</Button> </>, document.getElementById("root") ); Currently this works as intended, but is not hidden. I have thought about creating a function that exports only a button if the paramater is fulfilled as posted below;
import Logout from "./logout"; import Button from "react-bootstrap/Button"; import React from "react"; function logoffBut(){ if (localStorage.getItem("token") !== null) { return <Button onClick={event => Logout()}>Logout</Button>; } } export default logoffBut; then calling
<logoffBut /> in my render above, in place of the current logout button that is there. However when I log in and store the 'token' in local storage, it does not generate the logoffBut at this point, despite the token being correctly stored in my local storage?
I would just like some help to see how I should be writing this function to be checking if my 'token' in local storage is not null, and if it is not null, to then generate the logoff button. Thank you.