reject:router

Route

This is what make a single page app do not refresh.

It is a big topic, and here I want to make it as quick as possible to read.

  1. Install react-router, react-router-dom to your project by
    npm install --save react-router react-router-dom
  2. import {BrowserRouter} from “react-router-dom”; in your App.js
  3. Wrap your application whole App inside <BrowserRouter></BrowserRouter>
    <BrowserRouter>
       <div className="App">
          ...
       </div>
    </BrowserRouter>
  4. import {NavLink, Route, Link, Switch} from “react-router-dom”; or any combination of those in your container component.
  5. 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>
  6. 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>

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>
...

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>

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
  • export default withRouter(COMP_NAME)
  • Route information on this.props
  • route lazy loading
  • reject/router.txt
  • Last modified: 2020/09/22 12:28
  • by chongtin