OneBite.Dev - Coding blog in a bite size

Render custom HTML, CSS and Javascript in Astro MDX files

Today I learn how to render custom HTML, CSS and Javascript in MDX Astro file. This is how you do it

Using MDX in Astro can make your custom collection posts more flexible. Today I learn how to render custom HTML, CSS and Javascript in MDX Astro file.

Create a custom astro component

First, create a new component, name it for example Raw.astro

---
---

  <div>
    <slot />
  </div>

<slot /> is the way we tell this component to render whatever we have in it.

Use this component

In your mdx files, use this component

import { Raw } from '../components/Raw.astro'; // depend on your location
  <Raw>
    <h1> Custom HTML! </h1>
    <script>
      {`
      console.log('it worked!')
      `}
    </script>
  </Raw>

Watchout for inject a script tag in Astro MDX files, you need to use this format

<script>
  {`
      console.log('it worked!')
  `}
</script>

Curly brackets + backticks

Now you can create super flexible post on your Astro Content collection files

astro