Using onClick on Div elements in React

avatar

Borislav Hadzhiev

Last updated: Apr 26, 2022

banner

Photo from Unsplash

Using onClick on Div elements in React #

To set an onClick listener on a div element in React:

  1. Set the onClick prop on the div.
  2. The function you pass to the prop will get called every time the div is clicked.
  3. You can access the div as event.currentTarget.
App.js
const App = () => { const handleClick = event => { // 👇️ refers to the div element console.log(event.currentTarget); console.log('div clicked'); }; return ( <div> <div onClick={handleClick}>Hello world</div> </div> ); }; export default App;

react onclick div

We set the onClick prop on the div element, so every time the element is clicked, the handleClick function gets invoked.

If you need to access the div element in your handleClick function, access the currentTarget property on the event object.

The currentTarget property on the event gives us access the element that the event listener is attached to.

Whereas the target property on the event gives us a reference to the element that triggered the event (could be a descendant).

If you want to pass a parameter to the handleClick function, set the onClick prop to an inline arrow function.

App.js
const App = () => { const handleClick = (event, message) => { // 👇️ refers to the div element console.log(event.currentTarget); console.log(message); console.log('div clicked'); }; return ( <div> <div onClick={event => handleClick(event, 'hello')}>Hello world</div> </div> ); }; export default App;

Notice that we are passing a function to the onClick prop and not the result of calling one.

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 could use this approach to set the onClick prop on any other element, e.g. a button, a span, etc.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.