React Events
React Events
events are handled similarly to regular HTML events but with some differences.
React uses a synthetic event system that wraps the native browser events to provide a consistent interface across different browsers.
React Events
Here's an overview of how events work in React:
1.Event Handling:
function handleClick() {
console.log('Button Clicked');
}
<button onClick={handleClick}>Click me</button>
2.Event Object:
function handleClick(e) {
console.log('Button Clicked');
console.log('Native event:', e.nativeEvent);
}
3.State Updates:
function handleClick() {
// Assuming count is a state variable
setCount(count + 1);
}
4.Form Handling:
function handleInputChange(e) {
setInputValue(e.target.value);
}
<input type="text" value={inputValue} onChange={handleInputChange} />
5.Preventing Default Behavior:
function handleSubmit(e) {
e.preventDefault();
// Your form submission logic here
}
6.Event Propagation:
// Parent component
function handleChildClick() {
console.log('Child Clicked');
}
<ChildComponent onClick={handleChildClick} />