React Router
React Router is the standard routing library for react applications. It intercepts browser URL changes and renders the matching component without triggering a server round-trip, enabling single-page-application navigation.
Usage in burgerApp (v4)
// src/index.js
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<Provider store={store}><BrowserRouter><App /></BrowserRouter></Provider>,
document.getElementById('root')
);
// src/App.js
import { Route, Switch, withRouter } from 'react-router-dom';
<Switch>
<Route path="/checkout" component={Checkout} />
<Route path="/orders" component={Orders} />
<Route path="/logout" component={Logout} />
<Route path="/auth" component={Auth} />
<Route path="/" exact component={BurgerBuilder} />
</Switch>Key components:
BrowserRouter— uses the HTML5 History API for clean URLs.Switch— renders the first matchingRouteonly.Route path exact—exactprevents/from matching all paths.withRouterHOC — injectshistory,location,matchprops into a component not rendered directly by aRoute(used onAppto accesshistory.push()).
Programmatic Navigation
Used in BurgerBuilder to redirect unauthenticated users:
this.props.history.push('/auth');And in Checkout to advance through the checkout flow.
See Also
- react — the UI library
- single-page-application — the pattern this enables
- schwarzmuller-2021-react-burger-app — source repo