rediet yosef
rediet yosef

Reputation: 222

how to hide a component on specific routes in react.js

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>
    );
};

Upvotes: 0

Views: 1180

Answers (2)

MOHD SHAHZAIB
MOHD SHAHZAIB

Reputation: 550

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

Upvotes: 2

sid
sid

Reputation: 2037

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")
)

Upvotes: 1

Related Questions