Universal Router + History+ React

Ippei Tanaka
2 min readFeb 14, 2018

--

Recently, I made a store demo app to experiment with some modern technologies available in Javascript, like GraphQL, PostCSS, and so on. I used React and Redux for the front-end, and for the router of the React app, I used Universal Router, instead of React Router. I’d like to share how I integrated them.

I made a small project for this article. Check it out on my Github repository.

Create routes

First, I need to create routes for Universal Router, which is just a Javascript object literal.

routes

An “action” method can return any kind of value. It could be a string literal or a React element. A “next” function is given as the part of the argument of the action method. The “next” function is the action method of the corresponding child route. I nest a child React element with a parent one using this mechanism.

Create a router

With the routes, now I create a router.

Calling the “resolve” method of a router with a path string literal or a location object, I get a Promise object that gives me the value that the corresponding action method returns. In my case, the value is a React element.

Integrate a router and ReactDOM

Integrating them is pretty simple. I created a “render” method, which takes a location object and renders a corresponding React element within a DOM element.

Create a Browser History object

I used History library for this project. And, I wanted to prevent a new history state from being added to a history stack when the new state is the same as the previous state. So, I wrapped up the push method of the history object.

Put them all together

Finally, I integrate the history object with the render method.

Link Component

Additionally, I created Link Component. It’s handy to use for location transition. (This is like the Link Component from React Router.)

Conclusion

Universal Router works pretty well with React and History. It’s totally independent from React, so it’d be very flexible. And, since it’s a small library that only takes care of issues related with router, it’d be easy to learn and understand what it does. On the other hand, you’d need to implement some essential features like Link Component or redirect on your own, which other bigger libraries, like React Router, have as built-in features. Personally, I prefer Universal Router to React Router because I can implement a router with a regular Javascript object literal.

Thank you for reading my article!

External Links

Universal Router
History
React
My Github Repository

--

--