I have a React component which renders an image. That image has to capture the onClick event, but it doesn't. There is no reason for this behavior. Here is the code:
class MyComponent extends React.Component {
imageClick = () => {
console.log('Click!!!!');
}
render () {
return (
<div>
<img src='/myfolder/myimage.png' onClick={this.imageClick} />
</div>
);
}
}
I can't see why it doesn't shows me back the 'Click!!!!' message in the browsers console when click on the image. It gives me back no error, no warning, no nothing. I'm using Chrome 62.0.3202 running on Linux Mint.
When isolated this code it works, but within boilerplate it does not, which is my case.
What am I missing here?
To set an onClick listener on an image in React: Set the onClick prop on the image element. The function you pass to the prop will get called every time the image is clicked.
To use an image as a link in React, wrap the image in an <a> tag or a Link tag if using react router. The image will get rendered instead of the link and clicking on the image will cause the browser to navigate to the specified page.
Building the Lightbox File js. First, we'll import the Lightbox component from 'react-image-lightbox' and add the URLs of our images. To add the URLs create a const (outside of the class) called 'images' that is equal to an array of your image URLs: Next we'll add the constructor for our class.
class MyComponent extends React.Component {
render () {
const imageClick = () => {
console.log('Click');
}
return (
<div>
<img src={require('/myfolder/myimage.png')} onClick={() => imageClick()} />
</div>
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With