Table of Contents
Setting up layout
Custom Markdown elements
MDX and custom components
Directly operate subcomponents
Summarize
More information about MDX
Home Web Front-end CSS Tutorial Working With MDX Custom Elements and Shortcodes

Working With MDX Custom Elements and Shortcodes

Apr 06, 2025 am 09:35 AM

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>
Copy after login

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;
Copy after login

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;
Copy after login

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>
Copy after login

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;
Copy after login

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>
Copy after login

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}

);
Copy after login

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>
);
Copy after login

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:

  1. Create a default Layout component that helps format MDX output.
  2. Replace the default HTML element rendered from Markdown with a custom component.
  3. Use shortcodes to get rid of the hassle of importing components in each file.
  4. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;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.

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

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&#039;s like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

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.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

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

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

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

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

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

How to Use CSS Grid for Sticky Headers and Footers How to Use CSS Grid for Sticky Headers and Footers Apr 02, 2025 pm 06:29 PM

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

See all articles