Approach 3 Using arrow function
The React class component “App” features a button labeled “Click Me!” linked to a handleClick method, logging “Button clicked” when clicked. The component also displays a styled header with the text “GeekforGeeks.”
Example: This example implements the above-mentioned approach
Javascript
import React from "react" ; class App extends React.Component { handleClick = () => { console.log( "Button clicked" ); }; render() { return ( <div> <h1 style={{ color: "green" , fontSize: "3rem" , fontWeight: "bold" , }} > GeekforGeeks </h1> <button style={{ fontSize: "3rem" , fontWeight: "bold" , border: "2px solid black" , }} onClick={ this .handleClick} > Click Me! </button> </div> ); } } export default App; |
Step to Run Application: Open the terminal and type the following command.
npm start
Output:
How to bind an event handler in JSX callback ?
ReactJS is a JavaScript library focused on building user interfaces. JSX callbacks in React are used to associate event handlers with elements in JSX code. Event handlers, like those for button clicks or form submissions, are functions triggered by events. In React, event handlers are bound to elements in JSX using the on syntax (e.g., onClick for click events), and a callback function is assigned to handle the event. This callback function is typically defined using bind() or the arrow function.
Syntax:
<element onEvent={this.eventHandler} />
We will see how to bind the event handler in JSX using the below examples:
Table of Content
- Binding a click event handler to a button in JSX:
- Using constructor and bind method.
- Using arrow function: