In the React documentation and a bunch of examples in various projects, form submission is handled in this manner:
const FormComponent = () => {
const [val, setVal] = useState('');
const onChange = (e) => {
setVal(e.target.value);
}
const onSubmit = (e) => {
e.preventDefault();
console.log(val);
// handle submit logic using "val"
}
return (
<form onSubmit={onSubmit}>
<input type="text" value={val} onChange={onChange} />
<input type="submit" value="Submit" />
</form>
)
}
While in other places I've seen code like this
const FormComponent = () => {
const [val, setVal] = useState('');
const onChange = (e) => {
setVal(e.target.value);
}
const onSubmit = () => {
console.log(val)
// handle submit logic using "val"
}
return (
<div>
<input type="text" value={val} onChange={onChange} />
<button onClick={onSubmit}>Submit</button>
</div>
)
}
They both seem to achieve exactly the same thing. Which is the better way of doing it?
The difference is not connected to React per se, but with HTML semantics. The first example is the one correct one.
There are a lot of screen tools that require correct HTML semantics, such as accessibility tools, that will work better with correct HTML.
One example you can easily test is that with the first option, pressing enter while focusing on the input will trigger the onSubmit
(like it should, for a form) and on the second example it will not.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments