DEV Community

Sam Robbins
Sam Robbins

Posted on • Originally published at samrobbins.uk

2 1

Adding captions to images in MDX

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](https://example.com/favicon.ico "bravo")
Enter fullscreen mode Exit fullscreen mode

Yields the following items

{
  type: 'image',
  url: 'https://example.com/favicon.ico',
  title: 'bravo',
  alt: 'alpha'
}
Enter fullscreen mode Exit fullscreen mode

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 (
      <figure>
        <img src={props.src} alt={props.alt} />
        <figcaption>{props.title}</figcaption>
      </figure>
    );
  } else {
    return <img src={props.src} alt={props.alt} />;
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay