Reputation: 132
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.
Upvotes: 3
Views: 3853
Reputation: 389
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
Upvotes: 5
Reputation: 2039
Astro’s Markdown and MDX support is powered by remark. This means you can write a remark plugin to transorm certain parts of your content to fit your needs. remark is very powerful, although not always the easiest to get started with.
Markdown plugins in Astro are configured via your astro.config.mjs
file. For example, this shows adding an existing remark plugin:
import { defineConfig } from 'astro/config';
import remarkToc from 'remark-toc';
export default defineConfig({
markdown: {
// Applied to .md and .mdx files
remarkPlugins: [remarkToc],
},
});
An example remark plugin might look something like this
import { visit } from 'unist-util-visit';
function mapImages() {
function transformer(tree) {
visit(tree, "image", (imageNode) => {
// manipulate image
});
}
}
You can then import mapImages
into astro.config.mjs
and add it to your remarkPlugins
array.
Upvotes: 1