It's a library inspired by the Angular's Reactive Forms, which allows to create a tree of form control objects in the component class and bind them with native form control elements.
- UI independent.
- Zero dependencies.
- Nested forms.
- Subscribers for value & status changes of controls.
- Provides a set of validators & also supports custom sync & async validators.
- Better form management with
FormGroup
&FormArray
apis. - Customizable update strategy for better performace with large forms.
npm install react-reactive-form --save
import React, { Component } from 'react';
import { FormBuilder, Validators, Field } from "react-reactive-form";
export default class Login extends Component {
constructor(props) {
super(props);
// Create the controls
this.loginForm = FormBuilder.group({
username: ["", Validators.required],
password: ["", Validators.required],
rememberMe: false
});
}
handleReset=(e) => {
this.loginForm.reset();
e.preventDefault();
}
handleSubmit=(e) => {
console.log("Form values", this.loginForm.value);
e.preventDefault();
}
render() {
return (
<Field
control={this.loginForm}
render={({ get, invalid }) => (
<form onSubmit={this.handleSubmit}>
<Field
control={get("username")}
render={({ handler, touched, hasError }) => (
<div>
<input {...handler()}/>
<span>
{touched
&& hasError("required")
&& "Username is required"}
</span>
</div>
)}
/>
<Field
control={get("password")}
render={({ handler, touched, hasError }) => (
<div>
<input {...handler()}/>
<span>
{touched
&& hasError("required")
&& "Password is required"}
</span>
</div>
)}
/>
<Field
control={get("rememberMe")}
render={({handler}) => (
<div>
<input {...handler("checkbox")}/>
</div>
)}
/>
<button
onClick={this.handleReset}
>
Reset
</button>
<button
type="submit"
disabled={invalid}
>
Submit
</button>
</form>
)}
/>
);
}
}
Try out react-reactive-forms
in these sandbox versions of the Examples.
- Simple Form
- Sync & Async Validation
- User Registeration Form With Nested Forms
- Form Array With Dynamic Controls
- Update On Submit
Let's make React Reactive Forms better! If you're interested in helping, all contributions are welcome and appreciated.
And don't forget to star the repo, I will ensure more frequent updates! Thanks!