Inline Editing

Next.js + Contentful Tutorial: Part 4

The most advanced (and productive) form of editing with Stackbit is inline editing, which is made possible through the use of annotations.

These are simple HTML data attributes (data-sb-object-id and data-sb-field-path) that map content in Contentful to elements on the page. This enables editors to click directly in the preview, make a change, and see that change reflected in Contentful.

Here, we'll make the heading field in the hero component editable inline.

Set the Object ID

The first step is to declare the ID of the content object using a data-sb-object-id attribute. This points Stackbit to the origin of the content on the screen.

In Contentful, every entry has an automatically assigned identifier stored in its sys.id property, delivered from the API.

In the tutorial's code, the utils/content.js module is tasked with fetching data from Contentful and returning it as JavaScript objects. The fetched sys.id value is mapped to an id property in the returned objects:

The `sys.id` property is added to fetched JavaScript objects
The sys.id property is added to fetched JavaScript objects

Add the data-sb-object-id attribute to the top-level div of this component to set the object ID.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
export const Hero = (props) => {
  return (
    <div className="bg-gray-100 px-12 py-24" data-sb-object-id={props.id}>
      ...
    </div>
  )
}

This annotation associates the top-level div of the Hero component, and all elements under it, with the ID of the Contentful entry (of type hero) that is passed to the component as props.

Add the Field Path

Now that the component is annotated with the ID of the hero content object, we can use the data-sb-field-path data attribute to make fields within the component editable inline.

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
export const Hero = (props) => {
  return (
    <div className="bg-gray-100 px-12 py-24" data-sb-object-id={props.id}>
      ...
      <h1 className="mb-6 text-5xl leading-tight" data-sb-field-path="heading">
        {props.heading}
      </h1>
      ...
    </div>
  )
}

That's all you need to be able to edit the heading inline!

Update Heading Inline
Update Heading Inline

Like the previous two forms of editing, this will also update content in Contentful.

Content Updated in Contentful
Content Updated in Contentful