Use forms in react easily.
Run this command in a React project
npm i jibon-reactive-form
import React from "react";
import ReactiveForm from 'jibon-reactive-form/reactive-form'
import FormControl from 'jibon-reactive-form/form-control'
import FormGroup from 'jibon-reactive-form/form-group-bundle'
import Validators from 'jibon-reactive-form/validators'
export default class Home extends React.Component{
data = new ReactiveForm({
username: new FormControl('', [Validators.required, Validators.username]),
email: new FormControl('', [Validators.required, Validators.email])
})
render() {
return (
<form onSubmit={e=>this.submit(e)}>
<FormGroup form_control={this.data.get('name')} name={'name'} clicked={false} />
</form>
);
}
submit(e){
e.preventDefault();
console.log(this.data.value);
}
}
<FormGroup />
component accepts 7 props, 3 is required and 4 is optional.
form_control
is a required prop. It expects aFormControl
type value.name
is a required prop. It expects astring
type value. It will display in the placeholder of input.clicked
is a required prop. It expectsboolean
type value to know the form is already submitted or not.className
is an optional prop. It expects astring
type value. It passes className to the parentdiv
element.type
is an optional prop. It expects adate|email|file|number|password|text|select|textarea
type value. It determines the input type. Default istext
.options
is an optional prop. It expects a{name:string;value:string}[]
type prop. It populates option element in select element. It is kinda required prop when you useselect
as atype
prop.on_change
is an optional prop. It expects a(Event) => void
type function. Passed function runs every time input value changes.
FormControl
class expects 2 constructor argument, provides 5 property and 1 method.
value
expects astring
type value. It will pre-populate the input field. Default isempty string
.validators
expects a((value:string) => {[key:string]:any} | null) | ((*) => (value:string) => {[key:string]:any} | null)
type function. Every time the input changes this function will run. If the function returnsnull
then the input is valid. If the function returns other thannull|false
input becomes invalid and the input gets a new class namedis-invalid
.
value
returns the current value of the control.errors
returns the currently attached errors in the control.dirty
returns aboolean
value if the control's value is changed or not.touched
returns aboolean
value if the control is interacted with.valid
returns aboolean
value if the control is valid.
set_value(value:string)
expects 1string
argument that is passed to the value property.
FormGroup
class expects 1 constructor argument.
fields
expects a{[key:string]: FormControl}
argument.