Working With MDX Custom Elements and Shortcodes
MDX is a powerful feature of content such as blogs, slideshows, and component documents. It allows you to write Markdown without worrying about HTML elements, their formatting and location, and incorporate the magic of custom React components when needed.
Let's take advantage of this magic and see how to customize MDX by replacing the Markdown element with our own MDX components. In the process, we will introduce the concept of "short code" when using these components.
It should be noted that the code snippets here are based on GatsbyJS and React, but MDX can also be used with different frameworks. If you need to know the beginning of MDX, start here. This article extends this content in a more advanced concept.
Setting up layout
We almost always want to render MDX-based pages in a universal layout. This way, they can be arranged with other components on the website. We can specify the default Layout component using the MDX plugin we are using. For example, we can define a layout using gatsby-plugin-mdx
plugin as follows:
<code>{ resolve: `gatsby-plugin-mdx`, options: { defaultLayouts: { default: path.resolve('./src/templates/blog-post.js'), }, // ...其他选项 } }</code>
This requires that src/templates/blog-post.js
file contains a component that will render children
prop it receives.
<code>import { MDXRenderer } from 'gatsby-plugin-mdx'; function BlogPost({ children }) { return (</code> {children} ); } export default BlogPost;
If we create the page programmatically, we have to use a component called MDXRenderer
to achieve the same functionality, as described in the Gatsby documentation.
Custom Markdown elements
While MDX is a format that allows us to write custom HTML and React components, its power is that it renders Markdown with custom content. But what if we want to customize how these Markdown elements are rendered on the screen?
We can certainly write a remark plugin for it, but MDX provides us with a better and easier solution. By default, Markdown renders some of the following elements:
To replace these default values with our custom React component, MDX comes with a Provider component called MDXProvider
. It relies on the React Context API to inject new custom components and merge them into default values provided by MDX.
<code>import React from 'react'; import { MDXProvider } from "@mdx-js/react"; import Image from './image-component'; function Layout({ children }) { return (<mdxprovider components="{{" h1:><h1 classname="text-xl font-light"></h1></mdxprovider></code> , img: Image, }}> {children} ); } export default Layout;
In this example, any H1 title (#) in the MDX file will be replaced by a custom implementation specified in the prop of the Provider component, while all other elements will continue to use the default values. In other words, MDXProvider
is able to get the custom tags we wrote for the H1 element, merge them with the MDX defaults, and then apply the custom tags when we write title 1 (#) in the MDX file.
MDX and custom components
Custom MDX elements are great, but what if we want to mix our own components into it?
<code>--- title: 导入组件--- import Playground from './Playground';以下是关于我一直在构建的`Playground`组件的介绍:<playground></playground></code>
We can import the component into the MDX file and use it like any React component. Of course, while this works great for component demos in blog posts, what if we want to use Playground in all blog posts? It would be a pain to import them into all pages. Instead, MDX gives us the option to use shortcodes. The following is the description of the short code in the MDX documentation:
[Shortcode] allows you to expose components to all documents in your application or website. This is a useful feature for common components such as YouTube embeds, Twitter cards, or anything else that is often used in documents.
To include shortcodes in an MDX application, we must again rely on MDXProvider
component.
<code>import React from 'react'; import { MDXProvider } from "@mdx-js/react"; import Playground from './playground-wrapper'; function Layout({ children }) { return (<mdxprovider components="{{" h1:><h1 classname="text-xl font-light"></h1></mdxprovider></code> , Playground, }}> {children} ); } export default Layout;
Once we include custom components into the components
object, we can continue to use them without importing the MDX file.
<code>--- title: 演示概念---这是新概念的演示:<playground></playground> > 看,妈妈!不需要导入</code>
Directly operate subcomponents
In React, we get the top level API to use React to manipulate child components. We can use these APIs to pass new props to child components, thereby changing their order or determining their visibility. MDX provides us with a special wrapper component to access subcomponents passed in by MDX.
To add a wrapper, we can use MDXProvider
as before:
<code>import React from "react"; import { MDXProvider } from "@mdx-js/react"; const components = { wrapper: ({ children, ...props }) => { const reversedChildren = React.Children.toArray(children).reverse(); return {reversedChildren}>; }, }; export default (props) => (<mdxprovider components="{components}"></mdxprovider></code> {props.children} );
This example inverts child elements so that they are displayed in the opposite order of the order we wrote.
We can even animate all incoming MDX sub-elements as we please:
<code>import React from "react"; import { MDXProvider } from "@mdx-js/react"; import { useTrail, animated, config } from "react-spring"; const components = { wrapper: ({ children, ...props }) => { const childrenArray = React.Children.toArray(children); const trail = useTrail(childrenArray.length, { xy: [0, 0], opacity: 1, from: { xy: [30, 50], opacity: 0 }, config: config.gentle, delay: 200, }); return (</code> {trail.map(({ xy: [x, y], opacity }, index) => ( <animated.div key="{index}" style="{{" transform: x.interpolate> `translate3d(${x}px,${y}px,0)`), opacity }} > {childrenArray[index]} </animated.div> ))} ); }, }; export default (props) => ( <mdxprovider components="{components}"> <main>{props.children}</main> </mdxprovider> );
Summarize
MDX is designed with flexibility out of the box, but it can be made more powerful with plug-in extensions. Thanks to gatsby-plugin-mdx
, we can do the following in a short time:
- Create a default Layout component that helps format MDX output.
- Replace the default HTML element rendered from Markdown with a custom component.
- Use shortcodes to get rid of the hassle of importing components in each file.
- Directly manipulate child elements to change MDX output.
Again, this is just a small part of what MDX helps simplify static website content writing.
More information about MDX
- Introduction to MDX
- Front-end documentation, style guides and the rise of MDX
The above is the detailed content of Working With MDX Custom Elements and Shortcodes. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

CSS Grid is a collection of properties designed to make layout easier than it’s ever been. Like anything, there's a bit of a learning curve, but Grid is
