Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to home page if URL is invalid?

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?

like image 569
Rostyslav Skyba Avatar asked Nov 19 '18 13:11

Rostyslav Skyba


People also ask

How do I redirect a homepage to another URL?

Click the URL Redirects tab. In the upper right, click Add URL redirect. In the right panel, select the Standard or Flexible redirect type. A standard redirect is used to redirect one URL to another.

What is redirect page to specific URL?

A redirect is a way to send both users and search engines to a different URL from the one they originally requested. The three most commonly used redirects are 301, 302, and Meta Refresh.


2 Answers

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.

like image 189
MWO Avatar answered Oct 17 '22 03:10

MWO


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.

like image 42
Neel Patel Avatar answered Oct 17 '22 05:10

Neel Patel