chris bailey

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

Focus

Form

Mouse

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.