+1 vote
186 views
by (98.9k points)
Explain the event handling in React. Write a React code to create a button “Greet the User” and display an alert box saying “Hello!” on clicking that button.

1 Answer

0 votes
by (98.9k points)
 
Best answer

Event handling in React allows you to respond to user interactions, such as clicks, form submissions, and mouse movements. React event handlers are written in camelCase notation, and they are passed to an event attribute within JSX elements. When an event occurs, the event handler function is called, and it receives an event object as an argument. The event object contains information about the event, such as the type of event, the target element, and any additional event-specific details. React event handlers can use this information to perform actions, such as updating the state of a component or modifying the DOM.

 

// index.js

import React from 'react';
import ReactDOM from 'react-dom';

class GreetingButton extends React.Component {
  greetUser = () => {
    alert('Hello!');
  };

  render() {
    return (
      <div>
        <button onClick={this.greetUser}>Greet the User</button>
      </div>
    );
  }
}

ReactDOM.render(<GreetingButton />, document.getElementById('root'));

 

 

 

Related questions

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

559 users

...