Search code examples
reactjsgatsbygatsby-image

How to transform the Gatsby Image component into a figure


I'm looking to extend the gatsby-image component to make it a semantically correct figure and add a <figcaption> inside of it.

There is a Tag prop that allows it to render as a figure, but I couldn't figure out how to add the child.

Here is what I tried.

import Img from "gatsby-image"

const Figure = (props) => {
  return (
    <Img Tag="figure" fluid={props.fluid} alt={props.alt}>
        <figcaption>This is the caption of my amazing image.</figcaption>
    </Img>
  )
}

export default Figure

Solution

  • What you are trying to do there is to pass a children to <Img> component which is external, so you are not able to handle it. In other words, <Img> tag will have inside a <figcaption> and you don't know if it accepts children to render (it doesn't).

    Another approach that may work for you is to wrap this configuration inside a custom figure tag. Such as:

    import Img from "gatsby-image"
    
    const Figure = (props) => {
      return (
        <figure>
          <Img fluid={props.fluid} alt={props.alt}/>
          <figcaption>This is the caption of my amazing image.</figcaption>
        </figure>
      )
    }
    
    export default Figure
    

    The Tag prop is intended to change the wrapper, set by default as a <div> but doesn't allow you to add a caption despite being a <figure>.