Handling events with React

Event handling in React is similar to handling DOM element events. The difference compared to HTML event handling is that event naming uses camelCase in React. The following sample component code adds an event listener to the button and shows an alert message when the button is pressed:

import React from 'react';

const MyComponent = () => {
// This is called when the button is pressed
const buttonPressed = () => {
alert('Button pressed');
}

return (
<div>
<button onClick={buttonPressed}>Press Me</button>
</div>
);
};

export default MyComponent;

In React, you cannot return false from the event handler to prevent default behavior. Instead, you should call the preventDefault() method. In the following example, we are using a form, and we want to prevent form submission:

import React from 'react';

const MyForm = () => {
// This is called when the form is submitted
const handleSubmit = (event) => {
alert('Form submit');
event.preventDefault(); // Prevents default behavior
}

return (
<form onSubmit={handleSubmit}>
<input type="submit" value="Submit" />
</form>
);
};

export default MyForm;

Now, when you press the Submit button, you can see the alert and the form will not be submitted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.15.80