React - form example (uncontrolled class component)
In this article, we would like to show you how to use forms in React.
Below example shows how to make a form
as a controlled class component.
With createRef()
method we create references that will be used to get DOM input elements access. References are attached via ref
properties. In below example, references are attached to username
and password
inputs. When onSubmit
event occurs then usernameRef
and passwordRef
are used to create data
object (this.usernameRef.curent.value
, this.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 during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
class Form extends React.Component {
constructor(props) {
super(props);
this.usernameRef = React.createRef();
this.passwordRef = React.createRef();
}
handleSubmit = e => {
e.preventDefault();
const data = {
username: this.usernameRef.current.value,
password: this.passwordRef.current.value
};
const json = JSON.stringify(data, null, 4);
console.clear();
console.log(json);
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<label>Username: </label>
<input ref={this.usernameRef} type="text" />
</div>
<div>
<label>Password: </label>
<input ref={this.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.
Note:
Go to this article to see functional component example.