Events in React
React has its own event system that is compatible with the W3C (World Wide Web Consortium) event model. The only difference is the camelCase format required by the JSX syntax.
<button onCLick="handleClick()">
Click on me
</button>
Creating an event handler
An event handler is a function that is executed in response to an event.
function Button() {
const handleClick = () => {
console.log('clicked')
}
return <button onCLick="handleClick()">Click on me</button>
}
Syntetic events
A synthetic event is an object that simulates a native browser event, providing the same interface, regardless of the browser (cross-browser wrapper).
This is useful, for example, when you don't want the form to be submitted when the submit button is clicked.
import React, { useState } from 'react';
const AppForm = () => {
const [inputValue, setInputValue] = useState('');
const handleChange = (event) => {
// Accessing the synthetic event
setInputValue(event.target.value);
};
const handleSubmit = (event) => {
// Prevent the default form submission behavior
event.preventDefault();
// Handle form submission logic here
alert(`Form submitted with value: ${inputValue}`);
};
return (
<form onSubmit={handleSubmit}>
<label>
Input:
<input type="text" value={inputValue} onChange={handleChange} />
</label>
<button type="submit">Submit</button>
</form>
);
};
export default AppForm;