Set of rules that define a JavaScript program.
Handling events in React is quite similar to handling events on DOM elements. However, there are some syntax differences. React events are named using camelCase, rather than lowercase. Also, with JSX you pass a function as the event handler, rather than a string.
In HTML, event handling is done by returning a string of JavaScript code. In React, you cannot return false to prevent default behavior. You must call preventDefault
explicitly. Here's an example of how it's done in React:
function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); } return ( <a href="#" onClick={handleClick}> Click me </a> ); }
In this example, the handleClick
method is being passed to the onClick handler. This is a common pattern in React.
In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick
and pass it to onClick
, this
will be undefined
when the function is actually called. This is not React-specific behavior; it is a part of how functions work in JavaScript.
To bind the this
context, you can use the .bind()
method:
constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); }
Inside a loop, it is common to want to pass an extra parameter to an event handler. For example, if id
is the row ID, either of the following would work:
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
The above two lines are equivalent, and both attach a click event to the button that will call the deleteRow
method when clicked.
React implements a SyntheticEvent wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation()
and preventDefault()
, except the events work identically across all browsers.
React's event system is a great way to handle user interactions and control the flow of data in your application. By understanding how to handle events in React, you can create more interactive and dynamic applications.