Sub topic 2
Submitting a Form
Assume you know JavaScript objects, React components, JSX, props, and basic HTML forms. In React, a form usually handles its own submit event instead of allowing the browser to reload the page.
Submitting a form
Attach onSubmit to the <form>, not only to the button. Call preventDefault() to stop the browser's normal navigation. Then read, validate, and send the values.
import { useState } from 'react';
export default function SearchForm() {
const [query, setQuery] = useState('');
function handleSubmit(event) {
event.preventDefault();
console.log('Searching for:', query);
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="query">Search</label>
<input
id="query"
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<button type="submit">Search</button>
</form>
);
}A button inside a form submits by default. Set type="button" for a button that should not submit.
Uncontrolled inputs and refs
An uncontrolled input stores its current value in the DOM instead of React state. Use defaultValue for its initial value. A ref is a React object that gives you access to a DOM element.
import { useRef } from 'react';
export default function SearchForm() {
const inputRef = useRef(null);
function focusSearch() {
inputRef.current?.focus();
}
return (
<>
<input ref={inputRef} name="query" defaultValue="" />
<button type="button" onClick={focusSearch}>
Focus search
</button>
</>
);
}Use refs for imperative actions, such as focusing or selecting text. Do not use them as a replacement for state when the rendered UI must respond to every keystroke.
Reading a form with FormData
FormData reads successful form controls by their name attributes. It works well when you only need values during submission.
function handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.currentTarget);
const values = Object.fromEntries(data.entries());
console.log(values);
}Checkboxes are included only when checked. Multiple controls with the same name may require data.getAll('name').
Validating form values
Validation should run before sending data. Keep validation separate from rendering so it is easy to test.
function validate(values) {
const errors = {};
if (!values.email?.includes('@')) {
errors.email = 'Enter a valid email address.';
}
return errors;
}Call validate(values) inside handleSubmit. If the returned object has keys, show those errors and stop. Otherwise, submit the data.
Exercise
Why should a submit handler call preventDefault() before processing the form?
Show answer
It stops the browser's default page reload and navigation, allowing React to validate and submit the data itself.