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
-
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