[Support Guide] How to retrieve data attributes in Netlify Create

Learn how to extract and render all data attributes from a component’s properties in Netlify Create.

Netlify Create uses declarative data attributes to determine which parts of a page should be editable in our visual editor. This is called annotating a component. Read the full annotations reference here.

Passing Data Attributes Down the Stack

Consider a layout component that loops through data and dynamically resolves the component to render based on that data. This is a common pattern in Netlify Create sites. The code often looks like this:

{
  sections.map((section, index) => {
    const Component = getComponent(section.type)
    if (!Component) {
      throw new Error(`no component matching the page section's type: ${section.type}`)
    }
    return <Component key={index} {...section} data-sb-field-path={`sections.${index}`} />
  })
}

Every component that could potentially be rendered as <Component /> thus must include the prop passed as data-sb-field-path. Otherwise, that prop is not rendered to the page, and Netlify Create does not know how to make that portion of the page visually editable.

It would look something like this:

export default function SectionComponent(props) {
  return (
    <div data-sb-field-path={props['data-sb-field-path']}>
      <div>{/* do things here ... */}</div>
    </div>
  )
}

getDataAttrs Utility

To make this process less painful, Netlify Create starters come with a getDataAttrs utility method. This method can be imported into any component to extract all props that begin with data- and write them as attributes to the component’s wrapping element.

The section component from above then looks something like this:

import { getDataAttrs } from '../../../utils/get-data-attrs'

export default function SectionComponent(props) {
  return (
    <div {...getDataAttrs(props)}>
      <div>{/* do things here ... */}</div>
    </div>
  )
}

The beauty of this approach is that it will catch any prop beginning with data-, which means you only have add this line once, and then all data attributes will be supported.

Utility Does Not Exist

If your site does not have this utility, you can add it. Create a file and add the following code:

export function getDataAttrs(props: any = {}): any {
  return Object.entries(props).reduce((dataAttrs, [key, value]) => {
    if (key.startsWith('data-')) {
      dataAttrs[key] = value
    }
    return dataAttrs
  }, {})
}

Place the file anywhere in your codebase. Then you’re free to import it into your components, as shown with the section component above.

Hide Annotations in Production

You don’t have to ship to production with Netlify Create-specific code.

You can omit all data-sb-* attributes (used for annotations) in production by using the @stackbit/annotations package.