1
votes

I have the following react-router configuration

import React from 'react'
import { BrowserRouter, Route } from 'react-router-dom'

<BrowserRouter>
  <Route exact path='/sign-in' component={SignIn} />
  <Route exact path='/:username' component={Profile} />
</BrowserRouter>

When on a profile page like /dylan the Profile component matches and :username param is "dylan" like I would expect.

When navigating to the /sign-in route, the component gets rendered and the component get rendered too (with sign-in as the username)

What is the idiomatic solution with react-router v4 to prevent routes from matching multiple components?

versions:

  • react-router-dom 4.1.2
1
use the <Switch> componentazium
That's not a good piece of design. It's better to consider having /sign-in and /users/:username instead.Battle_Slug

1 Answers

3
votes

@Battle_Slug is right. It's actually better to differentiate the route /sign-in and /user/:username

But If you really need it, you can do it this way

function CheckInitialParam(props) {
  if (props.match.params.intialParam === 'sign-in') {
     return <SignIn />
  } else {
     return <Profile />
  }
}
<BrowserRouter>
    <Route path="/:intialParam" component={CheckInitialParam} />
</BrowserRouter>

Using <Switch>also right.

import React from 'react'
import { Switch, Route } from 'react-router-dom'

<BrowserRouter>
  <Switch>
    <Route exact path='/' component={Home} />
    <Route path='/sign-in' component={SignIn} />
    <Route path='/:username' component={Profile} />
  </Switch>
</BrowserRouter>

Reference : https://reacttraining.com/react-router/web/api/Switch