|
11 | 11 |
|
12 | 12 | What if you want custom UI interactions embedded in your Markdown? |
13 | 13 |
|
14 | | -By using `rehype-react` with the `htmlAst` field, you can write custom React components and then reference them from your Markdown files. |
| 14 | +By using `rehype-react` with the `htmlAst` field, you can write custom React components and then reference them from your Markdown files, or map generic HTML elements like `<ul>` or `<h2>` to your own components. |
15 | 15 |
|
16 | 16 | _Note: this functionality was added in version 1.7.31 of gatsby-transformer-remark_ |
17 | 17 |
|
@@ -143,6 +143,39 @@ In addition, you can also pass attributes, which can be used as props in your co |
143 | 143 |
|
144 | 144 | <interactive-counter initialvalue="10"></interactive-counter> |
145 | 145 |
|
| 146 | +## Mapping from generic HTML elements |
| 147 | +
|
| 148 | +You can also map a generic HTML element to one of your own components. This can be particularly useful if you are using something like styled-components as it allows you to share these primitives between markdown content and the rest of your site. It also means the author of the Markdown doesn't need to use any custom markup - just standard markdown. |
| 149 | +
|
| 150 | +For example if you have a series of header components: |
| 151 | +
|
| 152 | +```javascript |
| 153 | +const PrimaryTitle = styled.h1`…` |
| 154 | +const SecondaryTitle styled.h2`…` |
| 155 | +const TertiaryTitle styled.h3`…` |
| 156 | +``` |
| 157 | +
|
| 158 | +You can map headers defined in markdown to these components: |
| 159 | +
|
| 160 | +```js |
| 161 | +const renderAst = new rehypeReact({ |
| 162 | + createElement: React.createElement, |
| 163 | + components: { |
| 164 | + "h1": PrimaryTitle, |
| 165 | + "h2": SecondaryTitle, |
| 166 | + "h3": TertiaryTitle, |
| 167 | + }, |
| 168 | +}).Compiler; |
| 169 | +``` |
| 170 | +
|
| 171 | +And headers defined in markdown will be rendered as your components instead of generic HTML elements: |
| 172 | +
|
| 173 | +```markdown |
| 174 | +# This will be rendered as a PrimaryTitle component |
| 175 | +## This will be rendered as a SecondaryTitle component |
| 176 | +### This will be rendered as a TertiaryTitle component |
| 177 | +``` |
| 178 | +
|
146 | 179 | ## Caveats |
147 | 180 |
|
148 | 181 | Although it looks like we're now using React components in our Markdown files, that's not _entirely_ true: we're adding custom HTML elements which are then replaced by React components. This means there are a few things to watch out for. |
|
0 commit comments