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 code adds an event listener to the button and shows an alert message when the button is pressed:

class App extends React.Component {
// This is called when the button is pressed
buttonPressed = () => {
alert('Button pressed');
}

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

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:

class MyForm extends React.Component {
// This is called when the form is submitted
handleSubmit(event) {
alert('Form submit');
event.preventDefault(); // Prevents default behavior
}

render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="submit" value="Submit" />
</form>
);
}
}
..................Content has been hidden....................

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