Introducing Routing to a React Web App

A Noob Meets Web Apps, Episode 5

In previous episode I structured my React app using composition of components. Now it’s time to adopt react-router to go from poll list to single poll where user will vote.

$ npm install --save react-router-dom
$ npm install --save-dev @types/react-router-dom

Make first route

I want to make a route to highlighted polls, parametrizing language. I move HighlightedPolls.tsx to app/features/highlightedPolls/component.tsx defining a new module. So I can create routeInfo.ts inside that folder:

Note that ‘en’ language is respected

Don’t forget who I am

I am a noob. While this approach works, it is not correct. <Switch> expects all children to be <Route> or <Redirect> components. Clearly HighlightedPolls.Route should not be put there: instead, I will define a function that returns a proper react-router route:

Routing to poll detail

We need a component to display choices inside a poll. That will be the place where user could vote.

Drill down from polls to poll

The final step is to connect poll list to single poll detail. It should be trivial using <Link> component provided by react-router library. I’d like to make a step further by decoupling components from start: I don’t want Polls component to know nothing about routing to Poll.

Note that poll path is generated using props.match, the match generated by I18n route. This is because we need to form an URL with `/:language/poll/:id` pattern, not`/:language/highlighted/poll/:id`

Preserving Poll object

When you load Poll.route() you fire a fetch to download Poll object from API. This is a bit an overkill since we already have a Poll object stored inside Polls component.

Call me Muccy. I’m a Senior iOS Developer.