In this tutorial, you will learn how to create a higher-order component using React.js that will enable inline editing mode to work within preview mode. This tutorial is part of a series of posts about using Episerver as a headless CMS with React.js. In traditional Episerver MVC rending, using the PropertyFor() helper would traditionally handle wrapping any Episerver component with all the correct attributes to allow the inline editing function to work.

When you use Episerver within a headless context all of the responsibility for making things like getting inline-editing to work is up-to-you. This means it up-to-you to write the frontend to integrate with Episerver correctly. You will need to apply the correct attributes to all components.

In order to make inline editing work, you will need to decorate every Episerver property with the data-epi-edit attribute when in edit mode. Adding this code to every component would violate the DRY principle. When working with React.js the best way to apply this functionality is with a high-order-component. Explaining what a HOC is and how you can implement it within React is outside the scope of this tutorial, to find more information read this:

The first task to get inline editing to work is to determine if edit-mode is currently enabled for the current request. Let's begin...

How To Get Edit Mode

Within C# you can determine if a request is in edit mode in a few different ways. There are some useful helpers like, PageEdititng To see a real-life example, you can check out the code within the music festival sample site:

In Javascript, you will not have access to these helpers. So you will either need to pass the editMode status via the content API. The alternative approach is to check the client-side if the current request is made by the editor. You can do this by checking if the current URL contains '/EPiServer/CMS/Content', like so:

The Higher-Order Function

To create a higher-order component code that can be wrapped around a component is fairly simple. The purpose of the HOC is to apply the correct attribute if 1editMode` is enabled. The end HTML that you want to render will need to look something like this - where 'mainContent' is the main of a property of type rich-text:

The code to accomplish this could look like this:

Pass in editmode and the components name 'mainContent'. The component will be the react component. For this example, the component would render the rich-text property on a page.

Tips In case Inline Editing Does Not Work

If you want the block preview mode to work you will need to implement a special block preview controller. If you do not know how to do this, then you can find out more in How To Preview A Block In Episerver

Within the block preview if the attribute is being rendered but inline editing does not work. Using inspector, check the containing element. If the containing element also has the data-epi-edit attribute then this may break inline editing.