Adding captions to images in MDX

14 September 2020

Using MDX you can overwrite the default components that are provided by Markdown. In this blog I will use this to add captions to images.

The first thing to do is to look at the table of components for MDX, and here we can see that images are represented by img. By following the link we can see the markdown

![alpha]( "bravo")

Yields the following items

  type: 'image',
  url: '',
  title: 'bravo',
  alt: 'alpha'

To adapt this component, we are going to use title as the caption

Then we create a React component, where each of the keys are passed inside props

function MyImg(props) {
  if (props.title !== undefined) {
    return (
        <img src={props.src} alt={props.alt} />
  } else {
    return <img src={props.src} alt={props.alt} />;

A conditional statement is used here so that no excess formatting is introduced if no title is present. The standard figure layout is used as a tag is there specifically for captions

You can then pass this component to MDX in the method detailed here and the captions should not display themselves. You can then apply CSS or classes to the HTML tags in order to style it as you want.