My Experience of Working on Top 7 Ancient React Form Libraries
Whether you are a developer or an IT team leader, you want to keep your core technology up-to-date with the latest trends. If your core technology is JavaScript, you're here to the right place.
ReactJS offers form libraries to avoid rewriting tedious code while enjoying a better system and motivate you to generate a unique code.
In this blog, I'll recommend some of the best React form libraries that you must learn before starting your project.
So let's get started!
1. React-hook-form
React-hook- helps to decrease the pain of creating forms with React and optimized for them in TypeScript, which is a good thing. It is used to design uncontrolled components and avoid re-rendering caused by user inputs.
Installation
Install React hook form using a single command, and here it is:
$ npm install
react-hook-form
Weekly Downloads
203,030
Example
import React from 'react';
import { useForm } from 'react-hook-form';
function App() {
const { register, handleSubmit, errors } = useForm(); // initialise the hook
const onSubmit = (data) => {
console.log(data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstname" ref={register} /> {/* register an input */}
<input name="lastname" ref={register({ required: true })} />
{errors.lastname && 'Last name is required.'}
<input name="age" ref={register({ pattern: /\d+/ })} />
{errors.age && 'Please enter number for age.'}
<input type="submit" />
</form>
);
}
2. React-Formal
React-formal offers a form with controlled and uncontrolled components that decouples control from DOM state and works with JavaScript objects.
Installation
$ npm install react-formal
yup
Weekly Downloads
1910
Example
var yup = require('yup')
, Form = require('react-formal')
var modelSchema = yup.object({
name: yup.object({
first: yup.string().required('Name is required'),
last: yup.string().required('Name is required')
}),
dateOfBirth: yup.date()
.max(new Date(), 'You can be born in the future!')
})
// ...in a component
render() {
return (
<Form
schema={modelSchema}
value={this.state.model}
onChange={model => this.setState({ model })}
>
<fieldset>
<legend>Personal Details</legend>
<Form.Field name='name.first'/>
<Form.Message for='name.first'/>
<Form.Field name='name.last'/>
<Form.Message for='name.last'/>
<Form.Field name='dateOfBirth'/>
<Form.Message for='dateOfBirth'/>
</fieldset>
<Form.Submit type='submit'>Submit</Form.Submit>
</Form>
)
}
3. FormJs
FormJs aims to work on HTML and creating forms using JSON schema data and provide elements like radio buttons, checkboxes, select boxes, etc.
Installation
$ npm install
forms
Weekly Downloads
1017
Example
var forms = require('forms');
var fields = forms.fields;
var validators = forms.validators;
var reg_form = forms.create({
username: fields.string({ required: true }),
password: fields.password({ required: validators.required('You definitely want a password') }),
confirm: fields.password({
required: validators.required('don\'t you know your own password?'),
validators: [validators.matchField('password')]
}),
email: fields.email()
});
4. Redux Form
It is a set of action creators and reducers that allow you to create and implement complex customized forms quickly and work with Redux. It is comparatively simple compared to other similar tools, so it does not take the flexibility away.
Installation
$ npm install --save
redux-form
Weekly Downloads
382223
Example
import React from 'react'
import { Field, reduxForm } from 'redux-form'
const SimpleForm = (props) => {
const { handleSubmit, pristine, reset, submitting } = props
return (
<form onSubmit={handleSubmit}>
<div>
<label>First Name</label>
<div>
<Field name="firstName" component="input" type="text" placeholder="First Name"/>
</div>
</div>
<div>
<label>Last Name</label>
<div>
<Field name="lastName" component="input" type="text" placeholder="Last Name"/>
</div>
</div>
<div>
<label>Email</label>
<div>
<Field name="email" component="input" type="email" placeholder="Email"/>
</div>
</div>
<div>
<label>Sex</label>
<div>
<label><Field name="sex" component="input" type="radio" value="male"/> Male</label>
<label><Field name="sex" component="input" type="radio" value="female"/> Female</label>
</div>
</div>
<div>
<label>Favorite Color</label>
<div>
<Field name="favoriteColor" component="select">
<option></option>
<option value="ff0000">Red</option>
<option value="00ff00">Green</option>
<option value="0000ff">Blue</option>
</Field>
</div>
</div>
<div>
<label htmlFor="employed">Employed</label>
<div>
<Field name="employed" id="employed" component="input" type="checkbox"/>
</div>
</div>
<div>
<label>Notes</label>
<div>
<Field name="notes" component="textarea"/>
</div>
</div>
<div>
<button type="submit" disabled={pristine || submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
)
}
export default reduxForm({
form: 'simple' // a unique identifier for this form
})(SimpleForm)
5.React-form-builder
React-form-builder offers components an essential form of persistence using FormHandlerMixin and adds that components as default or be overridden.
Installation
$ npm i
react-form-builder2
Weekly Downloads
406
Example
var React = require('react');
var ReactDOM = require('react-dom');
var FormHandler = require('react-form-builder').Mixins.Handler;
var ExampleFormDef = {
type: 'form',
components: [
{
type: 'text-field',
dataKey: 'example',
displayName: 'Example'
}
]
};
var Example = React.createClass({
mixins: [FormHandler],
// using props
getDefaultProps: function() {
return {
formDef: ExampleFormDef
};
},
onSubmit: function(callback) {
console.log("FormData: ", this.state.formData);
callback();
},
render: this.renderForm();
});
ReactDOM.render(Example(), document.body);
Read more: [Top Reasons to Use ReactJS in 2020 (Where and When You Can Use ReactJS for Web Development)](https://www.bacancytechnology.com/blog/top-reasons-to-use-reactjs-in-2020
6. tcomb-form
tcomb-form implements DOM models in JS and validate functions for tcomb domain models. It makes your code easier to understand and adds additional information to forms.
Installation
$ npm install
tcomb-form
Weekly Downloads
2023
Example
import t from 'tcomb-form'
const FormSchema = t.struct({
name: t.String, // a required string
age: t.maybe(t.Number), // an optional number
rememberMe: t.Boolean // a boolean
})
const App = React.createClass({
onSubmit(evt) {
evt.preventDefault()
const value = this.refs.form.getValue()
if (value) {
console.log(value)
}
},
render() {
return (
<form onSubmit={this.onSubmit}>
<t.form.Form ref="form" type={FormSchema} />
<div className="form-group">
<button type="submit" className="btn btn-primary">Save</button>
</div>
</form>
)
}
})
7. Wingspan-forms
It allows you to generate an abstraction for dynamic grids as an active form library and powers its widgets using the KendUI controlled by the logic passed.
Installation
$ npm install
wingspan-forms
Weekly Downloads
2
Example
/** @jsx React.DOM */
'use strict';
var fieldInfos = {
firstName: { dataType: 'text', label: 'First Name', name: 'firstName' },
lastName: { dataType: 'text', label: 'Last Name', name: 'lastName' },
gender: { dataType: 'enum', label: 'Gender', name: 'gender',
options: {
metadata: { idProperty: 'value', nameProperty: 'label'},
dataSource: [{ value: 'male', label: 'Male'}, { value: 'female', label: 'Female'}] }
},
age: { dataType: 'number', label: 'Age', name: 'age' },
birthday: { dataType: 'date', label: 'Birthday', name: 'birthday'}
};
var MyForm = React.createClass({
getInitialState: function () {
return {
firstName: '',
lastName: '',
gender: '',
age: null,
birthday: null
};
},
render: function () {
var controls = _.map(fieldInfos, function (fieldInfo) {
return (
<AutoField
fieldInfo={fieldInfo}
value={this.state[fieldInfo.name]}
onChange={_.partial(this.onFieldChange, fieldInfo.name)}
isValid={this.isFieldValid(fieldInfo.name)} />
);
}.bind(this));
return (
<div className="MyForm">
<div>{controls}</div>
<pre>{JSON.stringify(this.state, undefined, 2)}</pre>
</div>
);
},
onFieldChange: function (fieldName, value) {
this.setState(_.object([[fieldName, value]]));
},
isFieldValid: function (fieldName) {
var val = this.state[fieldName];
return val !== null && val !== ''
? [true, '']
: [false, 'This field is required.'];
}
});
var AutoField = WingspanForms.AutoField;
React.renderComponent(<MyForm/>, document.body);
WingspanForms.ControlCommon.attachFormTooltips($(document.body));
Wrapping Up
Here is the list of different libraries that you can use to generate forms for React that directly work with DOM and support controllable and uncontrollable components.
It would be best if you had a quick peek into each library's features and select the one suitable for your needs.
If you are looking to build your upcoming project using ReactJS, I recommend you choose the best ReactJS Development Company that can guide you throughout your project.