SvelteKit Structured Text component with blocks

Hi Dato team!

According to your docs for your SvelteKit Structured Text component, itā€™s possible to render special nodes within structured text. There is also an example in the docs:

<script>
import { isBlock, isInlineItem, isItemLink } from 'datocms-structured-text-utils';
import { StructuredText } from '@datocms/svelte';
import Block from './Block.svelte';
import InlineItem from './InlineItem.svelte';
import ItemLink from './ItemLink.svelte';
</script>

<StructuredText
  data={blogPost.content}
  components={[
    [isInlineItem, InlineItem],
    [isItemLink, ItemLink],
    [isBlock, Block]
  ]}
/>

This works fine for me as long as I donā€™t need to pass any props to my Block.svelte. But how can I render this block when I need to pass any props to the component?

In my case, my ā€œBlock.svelteā€ component is a simple button that receives a label prop. Something like this:

<!-- Block.svelte -->
<script lang="ts">
	export let label: string
</script>

<button>{label}</button>

Thanks!
Nico

Hi Nico,

That sounds like it should be simple, but I couldnā€™t figure it out either, sorry :frowning: Iā€™ve escalated this question to a dev for you and will let you know as soon as we figure it out. Thanks for your patience and sorry for the delay!

1 Like

Hi @Nico :slight_smile:

The Block component receives two props:

  • the DAST node,
  • and the block itself.

Thereā€™s an example in the tests. Adapting your example could produce something like this:

<script lang="ts">
	import { isBlock, type Block } from 'datocms-structured-text-utils';
	import type { ButtonRecord } from './types';

	export let node: Block;
	export let block: QuoteRecord;
</script>

{#if block.__typename == 'ButtonRecord' && isBlock(node)}
    <button>{block.label}</button>
{/if}

Let me know if that helps! :slight_smile:

2 Likes

Works perfectly, thank you, @sistrall!

I suggest to add the info about the block being passed to the component to the component docs. :+1:

1 Like