Home > database >  How would you pass a Markdown component to a React or Preact component in Astro?
How would you pass a Markdown component to a React or Preact component in Astro?

Time:10-27

Similarly to how you can pass Markdown components to Astro components, I want to import one into a React/Preact component.

It didn't seem to be working directly when I imported the component into the React/Preact, so I tried passing them in from the parent Astro component like so:

 <DemoContent
  blog={(<Blog />)}
  tweet={(<TweetThread />)}
  highlight={(<HighlightClips />)}
  client:visible
/>

...but that gives me ERROR: Expected ">" but found "/".

What is the suggested way of doing this?

CodePudding user response:

(Follow-up from a discord conversation. Thanks for making this public!)

When passing Astro or Markdown components to a framework like Preact, you'll need to use "slots." You can use slot="prop-name" to wire those up like so:

<DemoContent>
  <Blog slot="blog" />
  <TweetThread slot="tweet" />
  <HighlightClips slot="highlight" />
</DemoContent>

Then, in your Preact component, you can access blog, tweet, and highlight as props. You'll render these similar to the {children} prop:

export function DemoContent({ blog, tweet, highlight }) {
  return (
    <section>
      {blog}
      {tweet}
      {highlight}
    </section>
   )
}

These will also map to Vue or Svelte slots if you happen to use those frameworks. Hope this helps!

  • Related