I'm new to reactjs and couldn't solve this problem. When I click the log in button, it goes to the home page, but the navbar and sidebar stay at the log in page. how can i fix this problem? Can't I handle this problem without putting the navbar and sidebar inside other components?
I finally solved it. I'll explain each part of the code.
First of all, import useState and useEffect from react
import { useState, useEffect } from 'react'
Now, we have to know the current path of the webpage. For that, we use useState to set the current path.
In function App(), we initialize the currPath and set its initial value to the current path.
const [currPath, setCurrPath] = useState(window.location.pathname)
As per the behavior of useEffect(), it is called whenever the elements of the page are modified. We use it to get the current path whenever we go to the page with a different path, in other words, when the elements of the page are modified.
useEffect(() => {
setCurrPath(window.location.pathname)
}, [])
Now, every time we go to a different page, the currPath gets updated. As we only want to display navbar and sidebar whenever the path is not /, i.e. not the login path, we write it as:
{currPath !== '/' && <><SidebarNav /><Navbar /></>}
The above snippet comes right under the opening <BrowserRouter> tag.
Note: Multiple JSX elements must be wrapped in an enclosing tag and hence both <SidebarNav /> and <Navbar /> are wrapped inside <> and </>.