Vanja's Blog

Subscribe to Blog via Email


Enter your email address to subscribe and receive notifications of new posts by email.

Social


Recent Posts


Top Posts & Pages


Categories


Tags


Share


React Router

A Quick Introduction to React Router.

Vanja PetreskiVanja Petreski

React Router is the standard routing library for React. It keeps your UI in sync with the URL. This short article will give you some info how to quickly start using it. If you remember my React Countries app and React articles – we will use that app and add routing features to it, for the sake of practicing React Router library. You can find the source code here.

Where to start

The App

We have a few new things in the app:

First thing I did is to refactor the app a bit, so that it’s suitable for React Router. If you check index.js you will see that I wrapped everything with BrowserRouter (btw, documentation says that HashRouter should be used for static servers and BrowserRouter for dynamic serving, but seems that BrowserRouter also works without any problem with static AWS S3). Then App.js has been refactored to contain only the layout (header, main) and routing information. Depending on the path/url, main content will be different – ReactCountriesContainer, CountryDetails, About. Check those components for more details and React Router usage.

 

Another important thing is withRouter. If your component is not rendered using Route, but tries to access router params (match, location, history) – it will get undefined. In this case you have to wrap your components using withRouter HOC. You can see the example in App.js – const HeaderWithRouter = withRouter(Header). Also check redux integration.

Outro

This was ultra short article, but I hope it can help you to quickly start with React Router!

Software Engineer & Digital Nomad

Comments 0
There are currently no comments.