markdownastrojsmdxjs

Custom components in Markdown / MDX on Astro


I would like to be able to replace the default code that Astro uses to render some Markdown elements.

For example, it would be nice that when I type :

Some Text

![image](image.png)

---

Some other text

I could get

<p>Some Text</p>
<div data-lightbox="true">
    <img
        class="w-2/3"
        src="image.png"
        alt="image"
    />
</div>
<div class="divider my-2" />
<p>Some other text</p>

So that it replaces the default code for the image and the divider.

Right now I just copy-paste the HTML / JSX code when I need it, but it would be nice to be able to have it automatically done.


Solution

  • It's actually pretty simple with mdx as mentioned in the docs Custom components with imported MDX and custom components to html .

    define your custom component, say maybe H1

    H1Component.astro

    ---
    const props = Astro.props;
    ---
    <h1 {...props} class="bg-red-100"><slot /></h1>
    

    use the above defined custom h1 component in your markdown files as below

    import H1Component from '../components/H1Component.astro';
    export const components = {h1: H1Component}
    
    # Red Coloured Custom H1 Component
    
    ...
    

    OR

    wherever you render the content pass your custom components as below

    <Content components={{...components, h1: H1Component }} />
    

    Output

    enter image description here