sanity icon indicating copy to clipboard operation
sanity copied to clipboard

Pass props down to styles (e.g. p, h3, h4, blockquote, etc.)

Open aadgrant opened this issue 3 years ago • 3 comments

I needed props passed down to my Styles elements and Styles serializers (e.g. p, h2, h3, h4, blockquote, etc.) so I've tweaked this in Sanity Content.

Example use case - previously the below blocks would not render a class="hello-world" on <blockquote />

const blocks = [
  {
    _key: '03ed74fca82b',
    _type: 'block',
    class: 'hello-world',
    children: [],
    markDefs: [],
    style: 'blockquote'
  }
]

<blockquote class="hello-world"></blockquote>

I largely copied the code for the existing render() function, only tweak being to filter out markDefs from props.

markDefs aren't required or passed down to the Element - if we wanted to change this, this code could be used:

const props = Object.fromEntries(Object.entries(item).filter(([key]) => key !== '_type').map(
    ([key, value]) => {
      if (key === '_key') return ['key', value || null]
      **if (key === 'markDefs') return ['markDefs', value?.length ? value : null]**
      if (!isElement || validAttrs.includes(key)) return [key, value]
      return []
    },
  ))

aadgrant avatar Oct 12 '22 14:10 aadgrant

Deploy Preview for nuxt-sanity-module canceled.

Name Link
Latest commit 2fd90af2520527135fff6397273c11c970789d4e
Latest deploy log https://app.netlify.com/sites/nuxt-sanity-module/deploys/634c22dab9b3560007ba881c

netlify[bot] avatar Oct 12 '22 14:10 netlify[bot]

Would you add some snapshot tests to cover these changes? :pray:

danielroe avatar Oct 12 '22 14:10 danielroe

Added tests, hope these are suitable!

Also added 'class' to validAttrs - not sure if this was excluded for any reason, but it means <p class="hello-world"> can render when a class is provided within the Sanity Blocks.

aadgrant avatar Oct 12 '22 17:10 aadgrant