React events are named using camelCase instead of lowercase (e.g., onClick instead of onclick), and you pass a function as the event handler, rather than a string.
Example of Event Handling:
const Button = () => {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click me</button>;
};In this example:
- The event
onClickis used to handle the button click. handleClickis the event handler function that is triggered when the button is clicked.
React supports most of the DOM event types, including:
- Mouse Events:
onClick,onDoubleClick,onMouseEnter,onMouseLeave, etc. - Keyboard Events:
onKeyDown,onKeyUp,onKeyPress. - Form Events:
onChange,onSubmit,onFocus,onBlur. - Input Events:
onInput,onChange. - Other Events:
onScroll,onLoad,onError, etc.
To pass arguments to an event handler, you can wrap the event handler function in another function.
Example of Passing Parameters:
const Button = ({ value }) => {
const handleClick = (message) => {
alert(message);
};
return (
<button onClick={() => handleClick(`Button clicked with value: ${value}`)}>
Click me
</button>
);
};In this example:
- The
handleClickfunction takes amessageargument, and we use an arrow function to pass thevalueas a parameter when the button is clicked.
In React, event handlers receive a SyntheticEvent object, which is a cross-browser wrapper around the native event object. You can access properties like target, type, preventDefault(), etc., just like with regular DOM events.
Example:
const Form = () => {
const handleSubmit = (event) => {
event.preventDefault(); // Prevents the default form submission
console.log('Form submitted!');
};
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
};In this example:
event.preventDefault()is used to prevent the form’s default behavior (which is to refresh the page).- The event object is automatically passed as the first argument to the event handler.
Handling input fields in forms is a common task. You can use the onChange event to update the state whenever the user types in an input field.
Example of Handling Input:
const TextInput = () => {
const [value, setValue] = useState('');
const handleChange = (event) => {
setValue(event.target.value); // Updates the state with the input value
};
return (
<div>
<input type="text" value={value} onChange={handleChange} />
<p>You typed: {value}</p>
</div>
);
};In this example:
- The
onChangeevent is triggered whenever the user types something. - The
handleChangefunction updates the state with the value from the input field (event.target.value).
.png)
.png)
.png)