Skip to main content

React applications

Setup

First of all, it is necessary to setup the connector by following the Setup section, copying the discovery-cms-connector.js file inside the public folder and adding the following inside the App.js file scripts:

<script async={true} src={'discovery-cms-connector.js'} />

Page generation

To retrieve the contents of a page, the useDiscoveryPage() hook is used and takes it as input two parameters, i.e. the slug used for the page and an object with options. The display of data in the html is done through <DiscoveryContext> and the <DiscoveryComponents> element.

Below is an example of using what has just been described:

import {DiscoveryContext, DiscoveryComponents, useDiscoveryPage} from '@discoverycms/connector';

function Page() {
const data = useDiscoveryPage('/home', {
/// options for the API
token: router.query.token
});

if (data === null) {
return;
}

return (
<DiscoveryContext.Provider value={data}>
<DiscoveryComponents />
</DiscoveryContext.Provider>
)
}

In this example, we first get the page data. Once the data is retrieved, we provide it to the DiscoveryContext and then we use DiscoveryComponents to create all the components of the page.

When a component is created in the React application it is assumed that it receives an id as a parameter (id associated with the component on the Discovery side), then using the useComponentData() method, to which the id is passed, the data is obtained. So, our component should have a structure similar to this:

import {useComponentData} from '@discoverycms/connector';

function Component({componentId}) {
const data = useComponentData(componentId);

return(
<div data-discovery-id={componentId}>
...
</div>
)
}

Using the React context is not mandatory. It is in fact possible to recover individual data components from the response payload by applying its own logic. However this approach is not recommended as this procedure is simplified by the connector through the use of context and therefore conditions must exist details for which it should not be exploited.

Finally, the use of context is not necessary with Contents as they do not include a graphical representation but only data, and it is therefore still necessary to manually create the structure of the page.