0

this is the screenshot of the app.js file I want to hide my navbar when the route is at some specific routes, I want the logic for hiding the nav be in the app.js:-

export default function App() {

    return (
        <React.StrictMode>
            <Router>
                <NavBar />
                <Routes />
                <Footer />
            </Router>
        </React.StrictMode>
    );
};
rediet yosef
  • 192
  • 1
  • 15

2 Answers2

2

you can use useLocation hook from react-router-dom to identify the path where you want to hide the navbar.

export default function App() {
    const { pathname } = useLocation();
    return (
        <>
              { pathname === "/some-path" ? null : <NavBar />  }
                <Routes />
                <Footer />
        </>
    );
};

Edit

Render the app component inside the index.js file, like this.

 
 ReactDOM.render(
  <React.StrictMode>
    <Router>
      <App />
    </Router>
  </React.StrictMode>,
  document.getElementById("root")
);

I think you forgot to remove the router from the app.js file

MOHD SHAHZAIB
  • 500
  • 2
  • 10
  • Uncaught TypeError: Cannot read property 'location' of undefined this error comes up and I have imported useLocation from react-router-dom – rediet yosef Aug 14 '21 at 18:56
  • Can you share a screenshot of your code? shahzaibmohammad07@gmail.com – MOHD SHAHZAIB Aug 14 '21 at 19:03
  • which version of react-router-dom is it? – sid Aug 14 '21 at 19:07
  • "react-router-dom": "^5.2.0", – rediet yosef Aug 14 '21 at 19:12
  • I got the issue, wrap your App component with the router. render( , appDiv ) – MOHD SHAHZAIB Aug 14 '21 at 19:20
  • I have edit the answer have a look at that. – MOHD SHAHZAIB Aug 14 '21 at 19:33
  • your updated answer worked but now when I use react-router to the specific page the navbar stays in its initial state i.e if I want to hide the navbar in the signup page and route to the signup page from another page the navbar doesn't unmount but when I reload the signup page the navbar disappears and after that, if I route to another page from the signup page the navbar stays hidden, I think it always needs a refresh to update, so is their a fix?? – rediet yosef Aug 15 '21 at 06:50
1

As noted regarding the error you mentioned in comments, it's caused by the BrowerRouter as its being used in the same file.

Solution:

Moving BrowserRouter one level up will solve as by the time you invoke useLocation() the router also comes into the picture.

So the index.js file should be like

ReactDOM.render(
  <React.StrictMode>
    <Router>
    <App />
    </Router>
  </React.StrictMode>,
  document.getElementById("root")
)
sid
  • 1,779
  • 8
  • 10