1

I've recently countered a problem while using react-router-dom. when i used my code like this:

<BrowserRouter>
  <div>            
    <Switch>
        <Route path="/home" component={HOME} exact />
        <Route path="/protected" component={PROTECTED} />
        <Route component={NoMatch} />
    </Switch>
  </div>
</BrowserRouter>

NoMatch route component worked fine, but when i tried to use some Auth component like this it didn't work:

<BrowserRouter>
  <div>            
    <Switch>
        <Route path="/home" component={HOME} exact />
      <Auth>
        <Route path="/protected" component={PROTECTED} />
      </Auth>
        <Route component={NoMatch} />
    </Switch>
  </div>
</BrowserRouter>

so I've read some docs and issues, and eventually reached to conclusion that i need to use only react-router-dom components.No external components or custom components.So my question here is there a work around this problem.Or I've to think of another approach for authentication routes.And if there is no work around, can someone suggest the best way to do this way of authentication inside <BrowserRouter/> component ?

1 Answers1

1

React Router will only render a single component inside a Switch. If the path doesn't match /home, it will check the second component which is Auth and always render that.

You could instead use the render prop of the Route component so that the second component won't match any route except the /protected route.

<BrowserRouter>
  <div>            
    <Switch>
        <Route path="/home" component={HOME} exact />
        <Route
          path="/protected"
          render={() => (
            <Auth><PROTECTED /></Auth>
          )}
        />
        <Route component={NoMatch} />
    </Switch>
  </div>
</BrowserRouter>
Tholle
  • 83,208
  • 13
  • 152
  • 148
  • 1
    that's great, but what if i has multiple protected routes, do i need to repeat this process ` ( )} />` –  Feb 19 '19 at 23:28
  • 1
    @sasharomanov Yeah, that works. If you need to repeat it many times, it might be worth creating your own [`PrivateRoute` component like in this answer](https://stackoverflow.com/questions/43164554/how-to-implement-authenticated-routes-in-react-router-4) tailored to your needs. – Tholle Feb 19 '19 at 23:30