DEV Community

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

Posted on • Updated on

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 ❤️

Top comments (0)