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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

đź‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay