Last updated: Apr 7, 2024
Reading timeยท2 min
To set an onClick
listener on an image in React:
onClick
prop on the image element.const App = () => { const handleClick = event => { // ๐๏ธ Refers to the image element console.log(event.target); console.log('Image clicked'); }; return ( <div> <img src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp" alt="car" onClick={handleClick} /> </div> ); }; export default App;
We set the onClick
prop on the image element, so every time the element is
clicked, the handleClick
function gets invoked.
<img src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp" alt="car" onClick={handleClick} />
handleClick
function, access the target
property on the event
object.const handleClick = event => { // ๐๏ธ Refers to the image element console.log(event.target); console.log('Image clicked'); };
pointer-events
set to none
.handleClick
functionIf you want to pass a parameter to the handleClick
function, set the onClick
prop to an inline arrow function.
const App = () => { const handleClick = (event, message) => { // ๐๏ธ Refers to the image element console.log(event.target); console.log(message); console.log('Image clicked'); }; return ( <div> <img src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp" alt="car" onClick={(event) => handleClick(event, 'hello')} /> </div> ); }; export default App;
Notice that we are passing a function to the onClick
prop and not the result
of calling one.
<img src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp" alt="car" onClick={(event) => handleClick(event, 'hello')} />
If you invoke the function when passing it to the onClick
prop, e.g.
onClick={handleClick()}
, it would get immediately called when the component
mounts.
You can use the same approach to set the onClick
prop on a local image.
import MyImage from './thumbnail.webp'; const App = () => { const handleClick = event => { // ๐๏ธ Refers to the image element console.log(event.target); console.log('bobbyhadz.com'); }; return ( <div> <img src={MyImage} alt="horse" onClick={handleClick} /> </div> ); }; export default App;
The example assumes that you have an image named thumbnail.webp
in the same
folder as the App
component.
For example, if you are importing an image from one directory up, you would
import as import MyImage from '../thumbnail.webp'
.
The image has to be located in the src
directory of your project.
src
prop on the img
tag in order to render the image.<img src={MyImage} alt="horse" onClick={handleClick} />
With images from an external URL, you set the src
prop of the image to the
complete URL.
With local images, you set the src
proper of the img
tag to the imported
image.