Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expand docs for custom components #5315

Merged
merged 2 commits into from
May 8, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ tags:

What if you want custom UI interactions embedded in your Markdown?

By using `rehype-react` with the `htmlAst` field, you can write custom React components and then reference them from your Markdown files.
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.

_Note: this functionality was added in version 1.7.31 of gatsby-transformer-remark_

Expand Down Expand Up @@ -143,6 +143,39 @@ In addition, you can also pass attributes, which can be used as props in your co

<interactive-counter initialvalue="10"></interactive-counter>

## Mapping from generic HTML elements

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.

For example if you have a series of header components:

```javascript
const PrimaryTitle = styled.h1`…`
const SecondaryTitle styled.h2`…`
const TertiaryTitle styled.h3`…`
```

You can map headers defined in markdown to these components:

```js
const renderAst = new rehypeReact({
createElement: React.createElement,
components: {
"h1": PrimaryTitle,
"h2": SecondaryTitle,
"h3": TertiaryTitle,
},
}).Compiler;
```

And headers defined in markdown will be rendered as your components instead of generic HTML elements:

```markdown
# This will be rendered as a PrimaryTitle component
## This will be rendered as a SecondaryTitle component
### This will be rendered as a TertiaryTitle component
```

## Caveats

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.
Expand Down