React Router

We have already learned how third-party components fit with Reagent. In this chapter, we'll implement React Router in the Tinycanva app.

React Router#

There are many options for SPA routing in the CLJS world. Most CLJS routers tend to be data-driven and work seamlessly on the frontend and the backend.

However, React Router is far more popular than any CLJS solution, and it plays well with React, perhaps better than most CLJS routers. One of the reasons for this is that React Router encapsulates routing into React components, making it easy to reason for.

So - we're going to use React Router for the Tinycanva application. We will assume that you are familiar with its concepts - if not, we suggest that you watch this JS tutorial on React Router by Dev Ed.

Routes required#

We need to be able to register and log in. We also need a list view that lists all the graphics a user has created. Then we'll want a route to edit a graphic by id, and finally a catch-all 404. These are the routes we therefore need to account for:

  • / (index page with links to log in and register)

  • /register

  • /login

  • /graphics (list view)

  • /graphics/:id

  • /not-found

Structuring routes#

There are multiple ways to structure a React app with React Router. Some developers define all the routes in the same place, while some let routes grow organically.

We don't have any opinion on what approach you should take, but for this course, we'll define the top-level routes in app.core and the children routes in the respective parent component - ie the /graphics/:id route will be defined in the component rendered by /graphics.

If this doesn't make sense, don't worry. We'll walk through each part in detail.

Installing React Router#

We need the package react-router-dom to get the React Router for the browser:

Once installed, the modules exposed by react-router-dom can be required in CLJS code using Shadow's require syntax:

The above statement is equivalent to:

Cleaning the core namespace#

The core namespace is the entry point of our single page application (SPA). We'll make the Router the root component of the application. But before that, we need to delete some code that we added in the last chapter. You should only have the ns definition, the main function, and the render function in the app.core namespace. Everything else can be purged.

Once done, app.core should be similar to what the create-cljs-app generated:

We also removed app.hello from the render function and from the :require form.

Require React Router components#

We need three components for our initial setup: BrowserRouter, Switch and Route. This can be achieved by adding the following vector to :require list:


This page is a preview of Tinycanva: Clojure for React Developers

Please select a discussion on the left.