In React, events are handled in a similar way as in HTML, but there are some syntactical differences, such as using camelCase for event names.
function MyButton() { const handleClick = () => { alert('Button clicked!'); }; return ( <button onClick={handleClick}>Click me</button> ); }
In React, the event object is normalized and is provided to the event handler. This object contains all the properties and methods related to the event.
function handleClick(event) { console.log(event.target); // Logs the element that was clicked alert('Event handled: ' + event.type); } <button onClick={handleClick}>Click me</button>
React uses synthetic events, which are a cross-browser wrapper around the native events. They are normalized so that they have consistent properties across different browsers.
function handleClick(event) { console.log(event.nativeEvent); // Native browser event alert('Synthetic event handled'); } <button onClick={handleClick}>Click me</button>
React implements event pooling, which means the synthetic event object is reused and cleared after the event handler is called. To access properties of the event asynchronously, you should call `event.persist()`.
function handleClick(event) { event.persist(); setTimeout(() => { console.log(event.type); // Now works asynchronously }, 1000); } <button onClick={handleClick}>Click me</button>
Binding event handlers inside the constructor is a common pattern in React, but it's often avoided in favor of other methods like arrow functions.
class MyComponent extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); } handleClick() { alert('Button clicked'); } render() { return ( <button onClick={this.handleClick}>Click me</button> ); } }
Arrow functions automatically bind `this` to the component instance, making them an elegant solution for event handler binding.
class MyComponent extends React.Component { handleClick = () => { alert('Button clicked'); }; render() { return ( <button onClick={this.handleClick}>Click me</button> ); } }
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!