DEV Community

Cover image for Image as a Link with Contentful and Gatsby JS
Thomas Cosialls
Thomas Cosialls

Posted on • Edited on

2 2

Image as a Link with Contentful and Gatsby JS

As rich as the Rich Text functionality of Contentful might be, it doesn't include a simple way to create clickable images, i.e images embedded in a HTML link element. Here is a quick workaround with a Gatsby JS frontent.

Create a custom model in Contentful

We are creating a new custom model called ImageWithLink that contains 3 simple fields:

  • title
  • image (type Media)
  • url (type Short text)

image

You can then use your ImageWithLink model in any Rich Text contents or as part of another model definition.

Integrate with GatsbyJS

I will only emphasize how to generate the custom image with link element when the ImageWithLink model is provided inside a Rich Text field. You need to make sure your GraphQL requests are working correctly and that you imported all packages/functions needed to process Rich Text elements in Gatsby ;) I chose to use a fluid image in my example.

[BLOCKS.EMBEDDED_ENTRY]: node => {
    const {__typename} = node.data.target
    const target = node.data.target

    return <a href={target.url}><img src={target.image.fluid.src} /></a>
}
Enter fullscreen mode Exit fullscreen mode

I hope this will help some of you !
Best ❤️

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay