2

In my react app I want to hide the Navbar for the PageNotFound component alone.

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Home from './components/Home';
import Login from './components/Login';
import About from './components/About';
import Contact from './components/Contact';
import Blog from './components/Blog';

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Navbar />
          <Routes>
            <Route exact path="/" component={Home} />
            <Route exact path="/login" component={Login} />
            <Route path="/about" component={About} />
            <Route path="/contact" component={Contact} />
            <Route path="/blog" component={Blog} />
            <Route path="*" component={NotFound} />
          </Routes>
        </div>
      </Router>
    );
  }
}

export default App;

I dont want to render different layouts for all routes. I just want hide the Navbar for PageNotFound Component. Is it possible to achieve that?

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Mohan Raj
  • 58
  • 8
  • Can you confirm which version of `react-router-dom` you have installed and want to use? You've `imported` the `Switch` component and are using the `react-router-dom@5` `Route` component APIs, but you've rendered all the routes into the `react-router-dom@6` `Routes` component. – Drew Reese May 23 '23 at 07:08
  • I think i forgot to remove the switch. I have used Route only. – Mohan Raj May 23 '23 at 07:15
  • Ok, then if you are using RRDv6 I believe the linked post addresses your question. – Drew Reese May 23 '23 at 07:16

1 Answers1

-1

You should create a layout for your pages, which includes the children inside of it.

import { Navbar } from "../Navbar/navbar";
import { Footer } from "../Footer/Footer";
export const Layout = ({ children }) => {
    return (
        <div className="layout d-flex flex-column ">
            <Navbar darkTheme={darkTheme} setDarkTheme={setDarkTheme} />
            <main className="d-flex justify-content-around flex-grow-1">
                {children}
            </main>
            <Footer />
        </div>
    );
};

On your routers, you can wrap the components with the Layout.

...
class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Navbar />
          <Routes>
            <Route exact path="/" element={<Layout> <Home/> </Layout>} />
            <Route exact path="/about" element={<Layout> <About/> </Layout>} />
            <Route path="*" component={NotFound} />
          </Routes>
        </div>
      </Router>
    );
  }
}
...

This way you can use different layouts for different pages. If you want to create a new layout for a new page you can create your own and it's easy to scale up like this.

Anjaan
  • 595
  • 5
  • 19