The React library provides synthetic events that abstract the native event handling of the browser. React creates and manages synthetic events to ensure consistency across browsers. The events are synthetic because they are wrappers around native browser events, not the actual events.
Components created in React can have event listeners attached to them. In the case of a button component, you can attach a click event handler. You receive a synthetic event object when you click the button, which React passes to your event handler.
Using the event parameter provided to the handler function, you can access properties and methods of the synthetic event object.
function handleClick(event) {
console.log(event.target.value); // Accessing target value of a clicked element
}
function MyComponent() {
return <button onClick={handleClick}>Click Me</button>;
As shown in this example, the handleClick function is called with information about the event when the button is clicked.
import React from 'react';
function handleClick(event) {
console.log('Button clicked!');
}
function MyComponent() {
return <button onClick={handleClick}>Click Me</button>;
}
import React, { useState } from 'react';
function handleChange(event) {
const inputValue = event.target.value;
console.log('Input value:', inputValue);
}
function MyComponent() {
const [inputValue, setInputValue] = useState('');
return (
<input
type="text"
value={inputValue}
onChange={handleChange}
/>
);
}
import React from 'react';
function handleLinkClick(event) {
event.preventDefault();
console.log('Link clicked! Default behavior prevented.');
}
function MyComponent() {
return (
<a href="https://api.com" onClick={handleLinkClick}>
Click Me
</a>
);
}