Gatsby: Adding event handlers to gatsby-image <Img /> elements

Created on 27 Mar 2018  Â·  5Comments  Â·  Source: gatsbyjs/gatsby

Description

Is it possible to add React event handler functionality via props to the element? I referenced the doc on gatsby-image as well as the sharp plugin and no event handlers are discussed or listed in the props table.

Is the current default implementation to wrap the element inside another element (i.e. div) and add the event handler to the wrapper? This worked fine for me but I wanted to clarify if it was possible to directly add event props to or if it were coming in a future release.

i.e.

Steps to reproduce

I tried inlining an alert (as above) as well as writing a simple event handler to be called but neither works. I wrapped the in a div and added the click handler to it and this worked as expected.

Expected result

The React event would fire as normal when clicking on the .

Actual result

Nada.

Environment

Added the images and handler code inside the about.js file of the 4th tutorial project. Not attempting in actual project at the moment.

File contents (if changed):

None

Most helpful comment

Please re-open. I find this pretty important

All 5 comments

With https://www.npmjs.com/package/create-react-ref we could do this for people. You interested in adding a PR?

Due to the high volume of issues, we're closing out older ones without recent activity. Please open a new issue if you need help!

Please re-open. I find this pretty important

Agreed. @KyleAMathews this issue is still relevant, so can the issue please be re-opened?

A workaround to this problem is to wrap the Img in a div containing the event props:
```javascript.jsx

It's not very elegant however, and results in HTML structure that looks a bit like this (lots of nested `div`s!):
```html
<div>
    <div class="gatsby-image-wrapper">
        <img ... />
        <picture>
            <img ... />
        </picture>
        <noscript>...</noscript>
    </div>
</div>
Was this page helpful?
0 / 5 - 0 ratings

Related issues

dustinhorton picture dustinhorton  Â·  3Comments

kalinchernev picture kalinchernev  Â·  3Comments

andykais picture andykais  Â·  3Comments

jimfilippou picture jimfilippou  Â·  3Comments

brandonmp picture brandonmp  Â·  3Comments