Consider this example (CodeSandbox):
import { useState } from "react";
export default () => {
const [email, setEmail] = useState("");
return (
<form method="post" action="/example">
<input type="text" name="first-name" />
<input type="text" name="last-name" />
<input
type="email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
<button type="submit">submit</button>
</form>
);
};
If you type in "foo" for the first name, "bar" for the last name, and "baz@example.com" for the email, the payload that is submitted to the server is first-name=foo&last-name=bar
, not first-name=foo&last-name=bar&email=baz@example.com
. This is because email is a controlled component whereas the other two are uncontrolled.
The most obvious thing to do would be to refactor the form to use all controlled components, but I'm looking for a way that would be easier and less time consuming.
Looks like I just forgot the name
attribute!
<input
type="email"
name="email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
/>
With the above, the payload that is submitted to the server is like so, as expected:
first-name=foo&last-name=bar&email=baz%40example.com