How to apply specific class to <Structured Text />

Hi!

Iā€™d like to be able to add specific (tailwind) class on my H1 headings. How can I do?
GitHub - datocms/react-datocms: A set of components and utilities to work faster with DatoCMS in React environments is unclear on the matter to meā€¦

You can add a custom rule for that! This should work:

import { renderRule, isHeading } from 'datocms-structured-text-utils';

<StructuredText
  data={data.blogPost.content}
  customRules={[
    renderRule(
      isHeading,
      ({ node, adapter: { renderNode }, children, key }) => {
        return renderNode(`h${node.level}`, { key, className: node.level === 1 ? 'TAILWIND' : null }, children);
      },
    ),
  ]}
/>
2 Likes

Works like a charmā€¦ just add the curly braces to the customRules.
Thanks. Would be worth being documented as a ā€œrecipeā€ imho.

1 Like

Piling on here, is there a way to add a class to all top-level nodes of a Structured Text element? One option would be to write a custom renderRule for each allowable node type (similar to the ā€œApply different formatting to top-level paragraphsā€ example here).

Iā€™ve been trying to think of a more streamlined option but so far I havenā€™t figured it out. Does anybody have a suggestion? Thank you!