Multi-routes to component with exact in React

I have a component which should be shown when you first load the webpage but also on a specific route.

So, I have the component Users and this one should be shown in 2 cases: “/” or “/users”.

Currently I do it like this:

<Switch>
    <Route path="/" exact component={Users} />
    <Route path="/users" exact component={Users} />
</Switch>

There are also other routes in the Switch, however not necessary to copy. I know it is possible to do multi routing:

<Route path={"/" | "/users"} component={Users} />

However this does not work because I cannot use exact. How can I achieve it in this way?

Answer

You need to use Redirect

import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';

Result :

<Switch>
 <Route path="/users" component={Users} />

 <Route exact path="/">
  <Redirect to="/users" />
 </Route>
</Switch>

Leave a Reply

Your email address will not be published. Required fields are marked *