Nekode
React

Event handling

basic event handling in react

Rifki ahmad fahrezi

Rifki ahmad fahrezi

Introduction

Event handling is the most fundamental understanding to make you website more interactive, even though you’re not using any frontend framework.

On this article we’re not going deep about event handling, but this article will cover a basic introduction of event handling in React, including how to:

  • Create an event
  • Passing an event handler as props

Create an event

To create an event in React, you just have to attach the event name to the element that will fire it, this is the example for event handling in React on a button element

function handler(){
	alert("hello world")
}
 
<button onClick={handler}>
	click me
</button>

Passing an event handler as props

Passing an event handler as a props is a common practice is React, by passing an event handler as props you can make your component more reuseable.

For example we’re going to make Button component that can accept an onClick event that will show an alert dialog with text halo my name is ... ****(the dots will replace to name variable from an arguments), here is the code

Button.jsx

import React from 'react'
 
export function Button({ handler }){
	return (
		<button onClick={handler} >
			click me
		</button>
	)
}

Explanation

  1. Add props handler to send the event handler function to the button element

    Button({ handler })

  2. Attach the handler props to the onClick event

    <button onClick={handler} >

By following this code you can make your button element can accept an event handler to the children element, example usage to the parent component

import React from 'react'
import Button from './components/Button'
 
export function App(){
	function handler(name){
		alert(`Halo my name is ${name}`)
	}
 
	return (
   <div>
         Halo
         <Button handler={()=> handler("Nekode")} />
   </div>
	)
}

Result

Handling multiple events

If you want to handle alot of events in your single element on component you use the rest parameter to the props, here is the example

import React from 'react'
 
export function Button({ ...props }){
	return (
		<button {...props}>
			click me
		</button>
	)
}

By using rest parameter, not only event handler but the rest of elements attributes like id, className, etc. you can also pass it to the props component, here is the result

On this page