Search code examples
javascripthtmlreactjsgatsby

Gatsby: img is a void element tag and must neither have `children` nor use `dangerouslySetInnerHTML`


I am trying to build a component with Gatsby Js that includes a image that is imported. However when a link is added with the anchor HTML tag, I am receiving img is a void element tag and must neither havechildrennor usedangerouslySetInnerHTML`.

Without <a> ... </a> there is no such error.

My code:

import React from "react"
import medium from "../images/medium.png"


const Socials = () => (
    <div>
        <a href="https://medium.com"> <img src={medium}> </img> </a>
    </div>
)
export default Socials

Stack trace:

  in img (at Socials.js:8)
    in a (at Socials.js:8)
    in div (at Socials.js:7)
    in Socials (at pages/index.js:44)
    in IndexPage (created by HotExportedIndexPage)
    in AppContainer (created by HotExportedIndexPage)
    in HotExportedIndexPage (created by PageRenderer)
    in PageRenderer (created by JSONStore)
    in JSONStore (created by RouteHandler)
    in RouteHandler (created by EnsureResources)
    in div (created by FocusHandlerImpl)
    in FocusHandlerImpl (created by Context.Consumer)
    in FocusHandler (created by RouterImpl)
    in RouterImpl (created by Context.Consumer)
    in Location (created by Context.Consumer)
    in Router (created by EnsureResources)
    in ScrollContext (created by EnsureResources)
    in RouteUpdates (created by EnsureResources)
    in EnsureResources (created by LocationHandler)
    in LocationHandler (created by LocationProvider)
    in LocationProvider (created by Context.Consumer)
    in Location (created by Root)
    in Root
    in _default

What is the correct way to add an URL link to an image?


Solution

  • You should be able to import the image into your component, and add it to the image src like this.

    import React from "react"
    import gatsbyIconImage from "../images/gatsby-icon.png"
    
    const IndexPage = () => (
      <>
        <a href="https://stackoverflow.com"><img alt="stack overflow" src={gatsbyIconImage}></img></a>
      </>
    )
    
    export default IndexPage
    

    However, if you put anything between the opening and closing <img> tags (even just a single space), gatsby appears to think it has child elements and will not compile properly.