Skip to main content

SitecoreContext series

This blogpost is part of a short series on the SitecoreContext object

In the previous blogpost ‘Sitecore JSS: Exploring the SitecoreContext Object’ I talked about the SitecoreContext object, what it is and what it offers. Let’s repeat it once more what it is:

The SitecoreContext object provides context-aware data to components within your Sitecore JSS app, and can for example be useful when you need to modify the behavior of the JSS app/website based on the current context. The SitecoreContext object contains data about the current request and the Sitecore environment and is populated by the Sitecore Layout Service.

In that blogpost I mentioned that there are various ways of accessing it. In this blogpost I’ll explore the ‘withSitecoreContext’ higher-order component (HOC) approach.

According to the React docs: In React, a higher-order component (HOC) is a function that takes a component and returns a new component. HOCs are a powerful pattern that allows you to reuse code, add additional functionality to a component, or abstract complex behavior into a reusable function.

To access data from the current Sitecore item within your Sitecore JSS components, you can use the ‘withSitecoreContext’ higher-order component (HOC) provided by Sitecore JSS. This HOC can be used to inject the Sitecore context – which includes route-level data – into any of your components. By default, JSS components typically obtain their data from a dedicated datasource item, but using this HOC allows you to access the data from the current Sitecore Context Item (current route) instead.

Let’s have a look at an example, such as a ‘Metadata’ component

In the above example, the ‘withSitecoreContext’ HOC is being used to wrap the ‘MetaData’ component (at line 20), which provides the component with the sitecoreContext prop that contains data from the current Sitecore Context Item provided by the Sitecore Layout Service. The sitecoreContext prop can then be used in the component (line 5/6) to access this data and render out the values.

Here’s in the end how the fields configuration was setup in Sitecore

Sitecore JSS: Exploring the withSitecoreContext higher-order component (HOC) Sitecore Field Setup

And this is in the end how it’s outputted…

Sitecore JSS: Exploring the withSitecoreContext higher-order component (HOC) output

And that’s it! As you can see it’s very easy with the ‘withSitecoreContext’ HOC to access Sitecore Context Item data.

And that concludes the 3 part series on the ‘SitecoreContext’ object.

Happy Sitecoring!