React - form example (uncontrolled components)
In this article, we would like to show you how to use React forms.
The below example shows how to use a form
as a functional uncontrolled component.
With React.useRef()
we create references that will be used to get DOM input elements access. References are attached via ref
properties. In the below example, references are attached to username
and password
inputs. When onSubmit
event occurs then usernameRef
and passwordRef
are used to create data
object (usernameRef.curent.value
, passwordRef.current.value
). That data
object can be later sent to some server or used to do some other operations - in our case we just print JSON in the console.
Practical example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines in your project.
// import React from 'react';
// import ReactDOM from 'react-dom';
const Form = () => {
const usernameRef = React.useRef();
const passwordRef = React.useRef();
const handleSubmit = e => {
e.preventDefault();
const data = {
username: usernameRef.current.value,
password: passwordRef.current.value
};
const json = JSON.stringify(data, null, 4);
console.clear();
console.log(json);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Username: </label>
<input ref={usernameRef} type="text" />
</div>
<div>
<label>Password: </label>
<input ref={passwordRef} type="password" />
</div>
<button type="submit">Submit</button>
</form>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<Form />, root );
Note: above solution is quite good but there are better ways how to manage forms with big amount of fields inside form.