Become a member
to unlock all features

    Use MDXProvider to Control the Rendering of Markdown Elements with Gatsby MDX

    Chris BiscardiChris Biscardi

    MDX allows you to control the rendering of any element from your markdown document, such as the heading, paragraphs, or code blocks. MDXProvider is a component that can be used to supply React components to control the rendering for these components.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: 00:00 Here, we have an MDX file and a running Gatsby project. You can see the result of the MDX file above in the Chrome window to the top left.

    00:09 To use MDXProvider to change the rendering of an element, such as the heading, or a paragraph, or the code block, we must use MDXProvider. MDXProvider is a component that we can place anywhere higher in the React tree than our MDXContent.

    00:27 The MDXContent will then get the list of components that we want to override from the MDXProvider through context. In our case, we'll be using wrapRootElement, which is a Gatsby browser and a Gatsby SSR API. This API lets us wrap the entire application with an MDXProvider.

    00:46 First, we need to import MDXProvider from mdx-js/react. Since MDX supports multiple frameworks, we need to specify which version we're using. Then we can create an object where the keys are the names of the elements that we want to replace, in this case, H1.

    01:02 The values are React components that will control the rendering. In this case, we've chosen to stay with an H1 tag, but we've chosen to change the color to hot pink. For every other prop, we're just passing it through.

    01:14 Finally, we're using the Gatsby wrapRootElement API to wrap the application with the MDXProvider. We pass the components that we want to the MDXProvider. If we save this, we see the application rebuild, and we see that our component is now controlling the rendering of the H1 tag.

    01:33 In a production application, you'll also want to copy this code into Gatsby SSR, so that when you run Gatsby build, the HTML is built using the MDXProvider's components for your MDX content.