2

I was looking for the simplest way to render the same component but from different paths.

I have the following so that both "/" and "/login" render the Login component.

import React from "react";
import { Route, Switch, Redirect } from 'react-router-dom';
import './App.scss';
import Login from "../../login/Login";

const App = () => {

   return (
      <div className="App">
         <div className="App-container">
            <Switch>
               <Route exact path={["/", "/login"]} component={() => 
                  <Login login={true} />}/>
               <Redirect to="/" />
            </Switch>
         </div>
      </div>
   );

}

export default App;

This does appear to work, however, it returns an error in the console.

Warning: Failed prop type: Invalid prop 'path' of type 'array' supplied to 'Route', expected 'string'.

I'm trying to do this...

<Route exact path={"/"} component={() => <Login login={true} />}/>
<Route exact path={"/login"} component={() => <Login login={true} />}/>

But with a shorter method, is this possible with react-router-dom? Any help would be greatly appreciated

mcclosa
  • 943
  • 7
  • 29
  • 59
  • 1
    Possible duplicate of [Multiple path names for a same component in React Router](https://stackoverflow.com/questions/40541994/multiple-path-names-for-a-same-component-in-react-router) – Arnaud Christ Mar 12 '19 at 08:59
  • @ArnaudChrist That is for `react-router`. The solution in that question is what I am using above, which is giving me an error in the console. – mcclosa Mar 12 '19 at 09:00
  • Did you try with the answer using regular expression string from Cameron in the mentioned post ? `path="/(home|users|widgets)/" ` – Arnaud Christ Mar 12 '19 at 09:03
  • Yes, just wasn't sure how to target `/` with regular expression? – mcclosa Mar 12 '19 at 13:31

2 Answers2

3

You could create an array that contains the paths / and /login and use map on that array to render the same thing for both paths.

<Switch>
  {["/", "/login"].map(path => (
    <Route
      key={path}
      exact
      path={path}
      render={() => <Login login={true} />}
    />
  ))}
  <Redirect to="/" />
</Switch>
Tholle
  • 108,070
  • 19
  • 198
  • 189
3

If you wish to render the same component on the several routes, you can do this by specifying your path as a regular expression

lets say you want to display 'Home' component for 'Home', 'User' and 'Contact' components then here is code.

<Route path="/(home|users|contact)/" component={Home} />
Yasir Ali
  • 117
  • 1