An intro to Event Handling in React with onClick example!
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.
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.
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!