3

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

4
  • 1
    Possible duplicate of Multiple path names for a same component in React Router Commented Mar 12, 2019 at 8: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. Commented Mar 12, 2019 at 9:00
  • Did you try with the answer using regular expression string from Cameron in the mentioned post ? path="/(home|users|widgets)/" Commented Mar 12, 2019 at 9:03
  • Yes, just wasn't sure how to target / with regular expression? Commented Mar 12, 2019 at 13:31

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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} />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.