mcclosa
mcclosa

Reputation: 1455

Prevent Navigation Component Rendering on Single Route but Render on every other Route

So I have a single Route /reminder, where I do not want my Navigation component, but I want the Navigation component to render on every other Route and I'm not sure how to go about this?

This is my App.js where I am using react-router-dom for my routing.

import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Navigation from "./components/navigation/Navigation";
import Reminder from "./components/reminder/Reminder ";

const App = () => {

  return (
    <>
      <Switch>
        <Route path="/reminder" component={Reminder} exact />
      </Switch>
      <Navigation />
      <MainContent>
        <Router>
          <Route path={"/"} component={Dashboard} exact />
        </Router>
      </MainContent>
    </>
  );
}

I had a look around for similar issues, but it's mostly for authenticated pages, this isn't for an authenticated page.

I don't want to go down the route of having to add the Navigation component into each of my 21 current routes, it seems like there should a better method?

With my current code above, it renders the Reminder component but still renders the Navigation component.

Upvotes: 0

Views: 240

Answers (1)

technicallynick
technicallynick

Reputation: 1592

You can access the match data using a custom hook from react-router. All you need to do is

import { useRouteMatch } from "react-router-dom";

function App() {
  let match = useRouteMatch("/reminder");

  // Do whatever you want with the match...
  return (
<>
  <Switch>
    <Route path="/reminder" component={Reminder} exact />
  </Switch>
  {!match && <Navigation />} <---Conditional rendering
  <MainContent>
    <Router>
      <Route path={"/"} component={Dashboard} exact />
    </Router>
  </MainContent>
</>
  );
    }

Also, while I didn't change this in your example, it's not generally a good idea to have a route outside of the router component. I'm actually a little surprised react-router-dom didn't throw an error for you.

Upvotes: 1

Related Questions