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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With