7

I am using React and React-router v4

Here is my route component:

<Switch>
              {/* <Route path='/blog' exact component={Blog} /> */}
              <Route path='/projects/:id' component={ProjectDetails} />
              <Route path='/career/:id' component={CareerDetails} />
              <Route path='/' component={withScrollPreservation(LandingPage)} />
              <Route component={withScrollPreservation(LandingPage)} />
            </Switch>

What is my question:

If user types something that is not valid from routes give I want it to redirect to home page. Consider this scenario running this locally:

localhost:4000/ - home page

localhiost:4000/invalidurl - should redirect back to localhost:4000/ and deleteting invalidurl from url

Any thoughts?

Rostyslav Skyba
  • 109
  • 2
  • 2
  • 8
  • You can make use of [Redirect](https://reacttraining.com/react-router/web/api/Redirect) component – Shubham Khatri Nov 19 '18 at 13:02
  • @ShubhamKhatri - I am having an issue when user entered manually on the browser like localhost:9090/{invalidurl}/{invalidUrl} . I have raised the question as well , link is https://stackoverflow.com/questions/64261462/react-router-dom-redirect-is-not-working-for-nested-routes-eg-localhost90 . Please give some idea , how to do it, – SakthiSureshAnand Oct 11 '20 at 10:55

2 Answers2

10

You can use

import { Redirect } from 'react-router-dom';

and add this route inside your switch:

<Route render={() => <Redirect to={{pathname: "/"}} />} />

It'll catch anything that has no route.

wvdz
  • 16,251
  • 4
  • 53
  • 90
MWO
  • 2,627
  • 2
  • 10
  • 25
7

If you want to redirect home page when type invalid path string so that follow this code....

<Switch>
   <Route exact path="/" component={Home} />
   <Route path="/login" component={Login} />
   <Route path="/signup" component={Signup} />
   <Route path="/user" component={User} onEnter={this.requireAuth}/>
   <Route path="*" component={Home} />
</Switch>

here i used * in path that means if invalid path string type then it auto redirect to home page.

Neel Patel
  • 2,028
  • 18
  • 17