Quick Tutorial - Routing with React
Williams Oluwafemi
Posted on December 24, 2019
So you built that beautiful web app, Man and God were pleased with it, but whenever you try to route your app using the anchor tag, you lose all your App data, and you wonder why, maybe the gods aren't pleased after all? Probably not, using an anchor tag generally fetches a fresh version of your html file(short version) and to route in react you would have to use a package called react-router-dom. First you need to install the package, on your command prompt/terminal run
npm install --save react-router-dom
then import the package into your app
import {BrowserRouter, Route, Link} from 'react-router-dom'
So now to create your components that you want to route between
const Homepage = () => {
return(
<div>This is hoempage</div>
<Link to="/aboutus" class="button primary">Click to go to About Us</Link>
)
}
const AboutUs = () => {
return(
<div>This is About Us
<Link to="/" class="button primary">Click to go to back home</Link>
</div>
)
}
const App = () => {
<div>
<BrowserRouter>
<div>
<Route path="/" exact component={Homepage}></Route>
<Route path="/aboutus" component={AboutUs}></Route>
</div>
</BrowserRouter>
</div>
}
now you can route between pages, you might be wondering what the exact keyword is doing there, well it has to do with the way the BrowserRouter works, it creates an object called history which keeps track of the current url the user is visiting and uses it to also update the url as a user switches from 1 component to another and the way it works is, it queries the url and compares to the path that user is trying to visit and if it finds an occurrence in that path it renders the component, for example you are trying to access /aboutus, the BrowserRouter takes a look at the first route and checks if it contains "/", in this case it, does, so it renders it. To avoid this behavior, we add the exact attribute to the route to tell the Router that this component should only be rendered if the url is exactly '/'
You can copy out this code and play around with it, to learn more about the behavior of the react router :)
Posted on December 24, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.