React Router Integration with Scrivito

If you have a React app and subsequently integrated it with Scrivito, you will need to decide on which content to serve via which URLs. Is all your content Scrivito-based, or do you want your app to also render components independently of Scrivito? In the latter case, in mixed mode, you’d require a routing mechanism, while in a Scrivito-only setting, you usually don't.

For delivering all Scrivito content under a specific URL path (e.g. “/special”), the routingBasePath configuration key is available. Of course, you can use it in other environments as well, e.g. when integrating Scrivito with a PHP-based web app.

In this tutorial, however, we will be using React Router for more flexibility.

Starting at version 1.2, Scrivito features a helper method, Scrivito.useHistory, that, when combined with a history-based routing solution like React Router, allows you to dispatch requests based on the URL path, and to update the browser history accordingly.

Note that the React app on which this tutorial is based has been created using create-react-app, so some file names and imports might be different from your app.

The code above first provides a browser history object and passes it to Scrivito. Then this history is used in the “App” component when rendering either the “/hello” page or Scrivito-based content using a “Router” switch. In this switch, the catch-all path="*" route matches everything except “/hello”. Of course, you can alternatively handle the Scrivito-based content via one or more routes as well. To keep the code lean, place the Scrivito-related components (the exemplary inner <div> above) in a wrapper component.

Above, the “/hello” URL path is meant to point to Scrivito-independent content, here represented by the “Hello” component:

As you can see, our router switch covers three URL path variants, “/hello”, “/hello/world” and “/hello/universe”. In contrast to the “/hello” route in “App.js”, we are using the exact prop here to prevent the route from being applied regardless of additional path components.