Overriding a browser's current location without breaking the back button or causing an infinite redirect can be tricky sometimes. In this lesson we'll learn how React Router v4 allows us to easily achieve a redirect without getting bogged down in browser history.
import React from 'react'; import { Link, Route, Redirect } from 'react-router-dom'; const Menu = () => ( <div> <h1>Menu</h1> <Link to="/menu/food">Food</Link> <Link to="/menu/drinks">Drinks</Link> <Link to="/menu/123">Redirect</Link> <Route path="/menu/:section([a-z]+)" render={({ match }) => { return <h3>Section: {match.params.section}</h3> }}> </Route> <Route path="/menu/:section(d+)" render={({ match }) => { return <Redirect to="/menu/food"></Redirect> }}></Route> </div> ); export default Menu;
So if we hit /menu/food or /menu/drink, we will go to:
<Route path="/menu/:section([a-z]+)" render={({ match }) => { return <h3>Section: {match.params.section}</h3> }}>
Becase :section([a-z]+) match 'food' or 'drink'.
If we hit /menu/123, we will go to:
<Route path="/menu/:section(d+)" render={({ match }) => { return <Redirect to="/menu/food"></Redirect> }}></Route>
It will render Redirect component, and redirect us to /menu/food