1

I made an error page and redirect to it if the route is incorrect. But when I open localhost, the main page is error. But I need '/main'

 <Route path="/activities/" exact>
</Route>
            <Route path="/error" component={ErrorComponent} />
            <Redirect from="*" to="/error" />
            <Route path="/">
              <Redirect to="/main" />
            </Route>
Festina
  • 327
  • 3
  • 17

2 Answers2

2

you need to move the <Redirect from="*" to="/error" /> at bottom of all routes and add exact in <Route path="/">

 <Route path="/activities/" exact>
 </Route>
 <Route path="/error" component={ErrorComponent} />
 <Route path="/" exact>
     <Redirect to="/main" />
 </Route>
 <Redirect to="/error" />
 

Link will also help you in redirecting to the error route

Tahir Iqbal
  • 315
  • 1
  • 9
2

The wildcard redirect <Redirect from="*" to="/error" /> is being called first and causes any route to be redirected to your <Route path="/error" component={ErrorComponent} /> route

Wrap your <Route /> and <Redirect /> components in a <Switch> component as follows:

import { Redirect, Route, Switch } from "react-router";

<Switch>
  <Route path="/activities/" exact />
  <Route path="/error" component={ErrorComponent} exact />
  <Route path="/main" exact />
  <Redirect from="/" to="/main" />
  <Redirect from="*" to="/error" />
</Switch>

https://reactrouter.com/web/api/Switch