Event Types in React (Live Playground)
React provides various event types to help you create interactive and dynamic user interfaces. In this tutorial, we'll explore different event types in React, including MouseEvent, KeyboardEvent, FormEvent, and more, with sample code and simple explanations.
MouseEvent
MouseEvents are triggered by user interactions with a mouse, such as clicking or hovering. Some common MouseEvent types in React are:
onClick
onDoubleClick
onMouseEnter
onMouseLeave
Here's an example of using the onClick
and onMouseEnter
events:
function App() {
const handleClick = () => {
console.log('Button clicked!');
};
const handleMouseEnter = () => {
console.log('Mouse entered button');
};
return (
<button onClick={handleClick} onMouseEnter={handleMouseEnter}>
Click me
</button>
);
}
KeyboardEvent
KeyboardEvents are triggered by user interactions with a keyboard, such as pressing or releasing a key. Some common KeyboardEvent types in React are:
onKeyDown
onKeyPress
onKeyUp
Here's an example of using the onKeyDown
event:
function App() {
const handleKeyDown = event => {
console.log(`Key pressed: ${event.key}`);
};
return <input onKeyDown={handleKeyDown} />;
}
FormEvent
FormEvents are triggered by user interactions with form elements, such as submitting a form or changing an input field. Some common FormEvent types in React are:
onSubmit
onChange
onBlur
Here's an example of using the onSubmit
and onChange
events:
function App() {
const [text, setText] = React.useState('');
const handleSubmit = event => {
event.preventDefault();
console.log(`Form submitted with: ${text}`);
};
const handleChange = event => {
setText(event.target.value);
};
return (
<form onSubmit={handleSubmit}>
<input value={text} onChange={handleChange} />
<button type="submit">Submit</button>
</form>
);
}
Other Event Types
React also supports other event types, such as TouchEvent, FocusEvent, and DragEvent, which can be used to handle various user interactions. You can find a full list of supported event types in the React documentation.
Conclusion
Understanding different event types in React is essential for building interactive and dynamic user interfaces. By learning about MouseEvent, KeyboardEvent, FormEvent, and other event types, you'll be better equipped to handle various user interactions in your React applications. With a solid grasp of event types in React, you'll be well on your way to becoming an effective React developer.