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>
    );
};
2
  • Seems like this might be useful for you stackoverflow.com/a/60736742/6130275 Commented Aug 14, 2021 at 18:48
  • I thought this was outdated because it was asked 4 years ago Commented Aug 14, 2021 at 18:55

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

7 Comments

Uncaught TypeError: Cannot read property 'location' of undefined this error comes up and I have imported useLocation from react-router-dom
Can you share a screenshot of your code? [email protected]
which version of react-router-dom is it?
"react-router-dom": "^5.2.0",
I got the issue, wrap your App component with the router. render( <Router> <App /> </Router>, appDiv )
|
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")
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.