Prismic slices and Dynamic tag in Solidjs

Dynamic tag in Solidjs and Prismic Slice use case.


According to the official docs, Dynamic component lets you insert an arbitrary Component.

It allows to use repeatable component and loop through it. It can be compared to Switch statement which check some criteria and insert component.

<Switch fallback={<BlueThing />}>
  <Match when={selected() === 'red'}><RedThing /></Match>
  <Match when={selected() === 'green'}><GreenThing /></Match>
</Switch> 

Here is Dynamic component part

 <Dynamic component={options[selected()]} />

How simple it is. 😆

Prismic CMS use case

I fiund it is useful when dealing with Prismic Slices. First, I need to create a component registry and loop through slices.

The registry will look like following

const Slices = {
  heading_slice: Heading1,
  code_slice: Code,
  paragraph_slice: Paragraph
};


//Heading1.jsx
export default function Heading1(props) {

    return (
        <div>
            <h1 class="text-xl text-yellow-600 py-3">{props?.content.header_rich_text_field[0].text || "Heading 1"}</h1>
        </div>
    )
}

Here Heading1, Code etc are declared in JavaScript modules. In our content section we have Prismic slices. Let’s loop through it.

<For each={props.post?.body}>
              {(post) => (
                <Dynamic
                  component={Slices[post.type]}
                  content={post.primary}
                ></Dynamic>
              )}
            </For>
             

Also note that we can pass props to each component, which is identical. Otherwise, you need a different logic.