React Router v4 Provides Multiple Routes

I am creating a SPA and I am trying to configure Routing in an application using the react-router-dompackage version 4.1.1.

The definition of my route is below:

<BrowserRouter>
  <div>
    <Route exact path="/" component={Login} />
    <Route path="/login" component={Login} />
    <Route path="404" component={NotFound} />
    <Route path="*" component={NotFound} />
  </div>
</BrowserRouter>

Basically, I want to configure routing so that any request to a page for which a route is not defined goes to the component {NotFound}.

How can this be achieved? When executing a query on a page /login, the above solution provides both Loginand NotFound.

Yours faithfully

+12
source share
3 answers

here is an example from the official tutorial how to avoid rendering multiple routes

import { Switch, Route } from 'react-router

    <Switch>
      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/:user" component={User}/>
      <Route component={NoMatch}/>
    </Switch>
+21

Switch . Switch

import {Switch} from 'react-router';

<BrowserRouter>
  <Switch>
    <Route exact path="/" component={Login} />
    <Route path="/login" component={Login} />
    <Route path="404" component={NotFound} />
    <Route path="*" component={NotFound} />
  </Switch>
</BrowserRouter>

<Switch> , . , <Route> , .

, /login, <Switch> <Route>. <Route path="/login"/> , <Switch> <Login>. /login /login *

Switch , , Routes Routes. , "/home" "/" , exact

 <Switch>
    <Route exact path="/" component={Login} />
    <Route path="/home" component={Home} />
  </Switch>
+10

I think the NotFound page is displayed due to the rule <Route path="*" component={NotFound} />. The Path property of the router accepts Any valid URL path that understands the path to regexp. So, '*' means that zero or more parameter matches

0
source

Source: https://habr.com/ru/post/1017282/


All Articles