Use a simple state variable and keep track of the login status in your App.js
. (for example - by useState() hook below)
const [isLoggedIn, setIsLoggedIn] = useState(false);
Pass a callback function to the Routes
component and then to the Login
Component.
<Routes onLogIn={()=>setIsLoggedIn(true)}/>
Routes.js
Assuming it's a functional component (use this.props for class component).
<Route exact path="/login" >
<Login onLogIn={props.onLogIn}/>
</Route>
You can then call the onLogIn()
function from the Login component and update the state.
Now, again in App.js
-
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [canShowNav, setCanShowNav] = useState(false);
const [currentComponent, setCurrentComponent] = useState(''); //default component shown
useEffect(()=>{ //for determining canShowNav's value
if(isLoggedIn)setCanShowNav(true)
else{
if(currentComponent === 'login'){ //add any other components you want where nav should not be shown
setCanShowNav(false)
}
else setCanShowNav(true)
}
}, [isLoggedIn, currentComponent])
return(
<Router>
{canShowNav && <SideNavigation onComponentChange={(component)=>setCurrentComponent(component)}/>}
<Routes onComponentChange={(component)=>setCurrentComponent(component)} onLogIn={()=>setIsLoggedIn(true)}/>
</Router>
)
Then call onComponentChange("componentName")
from the SideNavigation
whenever a link is clicked, passing the component's name which is clicked.
You can pass the onComponentChange
function to the login page too, to change the state when user clicks on Forgot Password
or anything like that and update the state.
Routes.js
<Route exact path="/login" >
<Login onLogIn={props.onLogIn} onComponentChange={props.onComponentChange}/>
</Route>
Let me know if it helps you or not!✌