Using React Components with Scrivito’s Model Classes

Using React Components with Scrivito’s Model Classes

As mentioned in the Introduction to Scrivito, CMS content is rendered in the browser by React components. In this short guide, we are going to explain what such components should be like.

Assigning a component to an object or widget class

When rendering a CMS object or widget, Scrivito uses the component of the model class to which the object or widget belongs. For assigning a component to an object or widget class, Scrivito.provideComponent is available. For example, assuming that there is a HeadlineWidget class that has a title attribute, you can have Scrivito render instances of this widget class by providing a suitable functional component:

You could also provide a class component instead. However, this is only recommended when using state (and in this case, it’s required):

The provided component is connected to Scrivito, meaning that it automatically loads the required data from the Scrivito backend and automatically updates as new data becomes available.

Connecting stand-alone components to Scrivito

There are components that are independent of a specific model class and thus cannot be assigned to any of them. Such components render layout elements like navigations or the search box but should also be integrated with Scrivito as well, so that their data is automatically loaded and updated. In order to achieve this, you can connect such a component to Scrivito using Scrivito.connect:

CMS object and widget data is loaded asynchronously from Scrivito’s backend. Scrivito.connect frees you from having to handle pending data. It also ensures that a component is rerendered after the data has been loaded or changed.

However, when accessing CMS data outside of rendering, for example inside an event handler like onClick, you require Scrivito.load: It allows you to work consistently with the data loaded in the background.

In a nutshell...

When writing a component for a CMS model class (representing a page, resource, or widget type) use Scrivito.provideComponent and pass a functional component to it, unless you need to handle state. In this case create a React.Component class and pass it to Scrivito.provideComponent.

With components not intended for a CMS model class, always create a React.Component class and connect it to Scrivito using Scrivito.connect.