React Event Handling

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Sam Hall

Sam Hall

Full stack developer and stand-up comic.