Skip to content

Instantly share code, notes, and snippets.

@5t3ph
Last active January 4, 2019 15:07
Show Gist options
  • Save 5t3ph/d3b5028fca256391ba298dec81eeef0f to your computer and use it in GitHub Desktop.
Save 5t3ph/d3b5028fca256391ba298dec81eeef0f to your computer and use it in GitHub Desktop.
Gatsby Custom Markdown Components - prevent wrapping with paragraph
/* Review the following article for more info on getting started with custom components.
* @link https://using-remark.gatsbyjs.org/custom-components/
*
* Example here demonstrates detecting if a custom component is being used
* If so, do not wrap it with a paragraph tag and invalidate DOM nesting
*/
import * as React from 'react';
import rehypeReact from 'rehype-react';
import * as Type from './Type';
import Card from '../modules/Card';
const renderAst = new rehypeReact({
createElement: React.createElement,
components: {
h1: Type.H1,
h2: Type.H2,
h3: Type.H3,
h4: Type.H4,
h5: Type.H5,
h6: Type.H6,
p: (props) => {
return typeof props.children[0] === 'object' ? (
props.children[0].props.children[0].startsWith('>') ||
props.children[0].type.displayName === 'Link' ||
['strong', 'em'].includes(props.children[0].type) ? (
<Type.P>{props.children}</Type.P>
) : (
props.children
)
) : (
<Type.P>{props.children}</Type.P>
);
},
card: Card,
},
}).Compiler;
interface IMarkdownRenderProps {
markdown: {};
}
const MarkdownRender: React.SFC<IMarkdownRenderProps> = ({ markdown }) => {
return renderAst(markdown);
};
export default MarkdownRender;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment