Route
This is what make a single page app do not refresh.
Quick Start
It is a big topic, and here I want to make it as quick as possible to read.
- Install
react-router
,react-router-dom
to your project bynpm install --save react-router react-router-dom
import {BrowserRouter} from “react-router-dom”;
in your App.js- Wrap your application whole App inside <BrowserRouter></BrowserRouter>
<BrowserRouter> <div className="App"> ... </div> </BrowserRouter>
import {NavLink, Route, Link, Switch} from “react-router-dom”;
or any combination of those in your container component.- Can create the <Link> or <NavLink> to the container class like:
<nav> <ul> <li><NavLink to={"/"} exact activeClassName={"my-active"}>Home</NavLink></li> <li><NavLink to={"/post"} activeClassName={"my-active"}>New Post</NavLink></li> </ul> </nav>
- To display the components based on the URL route, you can do:
<Route path="/" exact component={Posts}/> <Switch> <Route path="/post/:id" exact component={FullPost}/> <Route path="/post" exact component={NewPost}/> </Switch>
Link, NavLink
If we do a <a href=“…”>xxx</a> for a link, the page will refresh, so we need to use <Link>xxx</Link>
or <NavLink>xxx</NavLink>
to replace it. Details here: https://reactrouter.com/web/api/Link https://reactrouter.com/web/api/NavLink
They have the following main props:
- to
- The URL to go to
- exact
- Will use this route only if the URL match exactly as the one in
to
- activeClassName
- The class name add to this block if it is active, mostly of CSS make up
Example: Go to exact path / if this Home link is click, and if it is active, it should have a css class named my-active
... <li><NavLink to={"/"} exact activeClassName={"my-active"}>Home</NavLink></li> ...
Route
If the url route is match to the path props, show the component, or render the JSX. Note that any URL match the path will be loaded.
<Route path="/" exact component={Posts}/> <Route path="/" exact render={()=><div>Demo1</div>}/> <Route path="/" exact> Demo2 </Route>
Switch
If you only need the very first route to be load on match. You can use Switch.
<Switch> <Route path="/:id" exact component={Posts}/> <Route path="/" exact render={()=><div>Demo1</div>}/> </Switch
Additional
- export default withRouter(COMP_NAME)
- Route information on
this.props
- route lazy loading