Style Components Rendered By MDX with Theme UI in Gatsby

John Otander
InstructorJohn Otander

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

Theme UI provides a wrapper around the MDXProvider so you can add styling to components that are rendered in your MDX documents. The styling you add will not be leaked as global styles since it relies on React Context and Emotion. The values set in the styles object are theme-aware so you can ensure consistency when applying color and typographic styles to your content.

This lesson uses gatsby-plugin-theme-ui in order to seamlessly integrate Theme UI into a Gatsby site.

illustration for Theme UI


Theme UI

Instructor: [00:00] Here, we have a running Gatsby site with gastby-plugin-theme-ui and gatsby-plugin-mdx configured.

[00:06] First, we can open up Gatsby-plugin-theme-ui/index.js. This a shadowed file that overrides the default theme. First, we can create styles object which maps to all elements in MDX. First, we'll begin with the root so we can add typographic styling to all child elements.

[00:26] First, we can set fontWeight which pulls from our fontWeights object. We can set the fontFamily which pulls from our fonts object. Actually, we can set the lineHeights. With the root styling set, we now need to use the root component in order to persist styling to child elements.

[00:46] We can open up our layout, import Styled from theme-ui, then wrap our application. When Gatsby reloads we'll now see our styling being picked up.

[01:00] Back in our theme file we can begin adding additional styling to our pre. Let's invert it by setting the background color to the text and the text color to the background color.

[01:14] We can further improve this by adding some padding. We'll set it to be an array of three, four, five so on mobile it'll pick up the third step of our space scale, for tablet four, and five for desktop. Let's set border radius as well. Not bad.

[01:32] It's also common to want to customize color of a link. We can do so by adding an A object for anchor in our styles. Here we'll set the color to primary, which will pull from our colors object. It's a blue jean blue.

[01:47] You can also apply pseudo classes. Here on hover let's get rid of the underline. Something useful about theme-ui is you can reach these components outside the context MDX. You just need to import style like we did root.

[02:04] Here we can use the pre tag again and we'll see the inverted styling. All together we've imported style from theme-ui and then wrapped our layout and styled that root to pick up typographic styling. In our theme we've also specified a styles object where we've set styling for root, pre, and anchors.