DEV Community

Chinwendu Agbaetuo
Chinwendu Agbaetuo

Posted on • Updated on

Hide/Show Navbar and Footer in React Application

Working on an application, that required a registered users interface and admin interface, I came across an issue - hiding the navbar and footer in the admin part. After countless research on the internet, I was able to make sense of what the possible solution entailed.

//app.js
import { Route, withRouter } from 'react-router-dom';
import Navbar from 'Components/Layout/Navbar';
import Footer from 'Components/Layout/Footer';
import Home from 'Pages/Home';

//Admin Imports
import Dashboard from 'Pages/Admin/Dashboard';
import DisplayProducts from 'Pages/Admin/DisplayProducts';

const App = ({ location }) => {
   // Array of excluded routes to hide navbar/footer
  const excludedRoutes = ['/admin/dashboard', '/admin/products'];

   return (
      {!excludedRoutes.includes(location.pathname) && <Navbar />}

      <Route path="/" component={Home} exact />
      <Route path="/dashboard" component={Dashboard} exact/>
     <Route path="/products" component={DisplayProducts} exact/>

    {!excludedRoutes.includes(location.pathname) && <Footer />}
  )
};

//withRouter gives access to location props
export default withRouter(App)
Enter fullscreen mode Exit fullscreen mode

The final step...

//index.js

import React, { StrictMode } from 'react';
import ReactDOM from 'react-dom';
import App from './App';

//Router ensures the URL matches the UI
import { BrowserRouter as Router } from 'react-router-dom';

ReactDOM.render(
  <StrictMode>
      <Router>
        <App />
      </Router>
  </StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Hope this helps.

Top comments (0)