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.
react-router, react-router-dom to your project by npm install --save react-router react-router-dom
import {BrowserRouter} from “react-router-dom”; in your App.js<BrowserRouter>
<div className="App">
...
</div>
</BrowserRouter>
import {NavLink, Route, Link, Switch} from “react-router-dom”; or any combination of those in your container component.<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>
<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:
toExample: 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
this.props