Handling Events in React
Handling events in React is similar to how we would handle them on the DOM. There are a few syntactic differences, and we’ll review some important ones here. One main difference you’ll notice is the use of camelcase instead of all lowercase when dealing with DOM.
Keyboard
- onKeyDown will be called when a key is depressed
- onKeyPress is called when a key is released but before onKeyup
- onKeyUp is called at the end after onKeyPress
Focus
- onBlur is called when a target loses focus
- onFocus is called when a target receives focus
Form
- onChange is called when a form control changes the value
- onInput is Identical to onChange and is preferred of the two.
- onSubmit is a special prop for
<form>elements that is called when a<button type="submit">is pressed or return is hit within a field.
Mouse
- onClick mouse button, press, and release.
- onMouseUp called after onClick.
- onMouseOver is called when the mouse moves directly over an element.
- onMouseEnter is when the mouse moves over a part of its children.
Example form usage
Basic form controls:
import React, { useState } from 'react';
const ContactForm = () => {
const [email, setEmail] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
// send email code
setEmail('');
setMessage('');
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={(e) => setEmail(e.target.value)}
value={email}
placeholder="enter email"
/>
<input
type="text"
onChange={(e) => setMessage(e.target.value)}
value={message}
placeholder="Enter a message"
/>
<button>Send</button>
</form>
);
}; We use onChange to update our state every time the input for the associated item is changed and onSubmit to execute whatever code we need to send off the message form and then clear the state and input values.