DEV Community 👩‍💻👨‍💻

Sam Robbins
Sam Robbins

Posted on • Originally published at

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]( "bravo")
Enter fullscreen mode Exit fullscreen mode

Yields the following items

  type: 'image',
  url: '',
  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 (
        <img src={props.src} alt={props.alt} />
  } 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)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.