Show pageBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== 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 by <code> npm install --save react-router react-router-dom </code> - ''import {BrowserRouter} from "react-router-dom";'' in your App.js - Wrap your application whole App inside <BrowserRouter></BrowserRouter><code> <BrowserRouter> <div className="App"> ... </div> </BrowserRouter> </code> - ''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: <code> <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> </code> - To display the components based on the URL route, you can do:<code> <Route path="/" exact component={Posts}/> <Switch> <Route path="/post/:id" exact component={FullPost}/> <Route path="/post" exact component={NewPost}/> </Switch> </code> ===== 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** <code> ... <li><NavLink to={"/"} exact activeClassName={"my-active"}>Home</NavLink></li> ... </code> ===== 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. <code> <Route path="/" exact component={Posts}/> <Route path="/" exact render={()=><div>Demo1</div>}/> <Route path="/" exact> Demo2 </Route> </code> ===== Switch ===== If you only need the very first route to be load on match. You can use Switch. <code> <Switch> <Route path="/:id" exact component={Posts}/> <Route path="/" exact render={()=><div>Demo1</div>}/> </Switch </code> ===== Additional ===== * export default withRouter(COMP_NAME) * Route information on ''this.props'' * route lazy loading reject/router.txt Last modified: 2020/09/22 12:28by chongtin