React Event Handling

Sam Hall
2 min readNov 16, 2021

An intro to Event Handling in React with onClick example!

Image courtesy of css-tricks.com

An “event handler” is a react feature in which actions are performed based on user interaction with specific elements on a browser’s interface. When an element with an event handler is interacted with, some other code is triggered to change the display, collect some data, etc. Syntactically, an event handler in React is written in camelCase and will point to a function encased in curly braces, like so:

onClick={eventHandlerFunction}

Here are some examples with the object of the event handler’s effect italicized:

onMouseover — an action is triggered when the user moves the mouse over the element.

onSubmit — an action is triggered when the user clicks a form’s submit button.

onSelect — an action is triggered when the user selects text.

onClick — an action is triggered when an element is clicked.

The last example, onClick, is a very common event handler and often used on button elements.

A Button component in App
The code within our Button Component
The button element and event handler

Within the Button Component of our example, we have the event handler attached to our button element. The event handler points to a function that should execute some code when the button is clicked.

handleButtonClick function

When the handleButtonClick function is triggered by our onClick event handler, the console should log “The button has been clicked!”

Each time we click the button, the console logs our message!

Further Reading and Sources

--

--