Event handling in functional component in Reactjs


reacIn HTML/JavaScript we used to wrap the event handler in double quotes (” “), in Reactjs the first thing we remember is we have to use curly braces for passing event handler. The second thing is that it is a convention that event handler name follow the camelCase format.

How do we create and use event handler in Reactjs ? We have two method,

  • Using a regular function

  • Using an inline arrow function

Regular function

Using the regular JS function we can pass it to the event handler as follows

import React from 'react'

function Button2() {
   
   function handleClick ()  {
    alert('Button 2 - clicked')
  }
  return (
    <div>
      {/* A Regular function */}
      <button onClick={handleClick}>Button2</button>
    </div>
  )
}
export default Button2

Arrow function

import React from 'react'

function Button1() {

  return (
    <div>
      {/* Inline Arrow function in return Statement */}
      <button onClick={()=> alert('Button1 clicked')}>Button1 - Arrow Fun 1</button>
    </div>
  )
}

export default Button1

An arrow function is a simple function without a name, this is also a feature included in React. It can be useful to write a small piece events.

Since functional component rendered by parent component, there is no difference in using the two method. I will pick the arrow function for small job.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.