React-forms is here to simplify your forms.
npm install @gferrand/react-forms
npm i @gferrand/react-forms
`
Be sure to receive at least the version 2.X.X.
... and that's it ! You can now import everything you need inside your project.
Creating your form
First, you will import Form inside your code.
`javascript
import { Form } from '@gferrand/react-forms';
`
Form, and all our inputs are based on the ES6 classes, to use them you will have to put the keyword new in front of them.
Instanciate your form inside your constructor, or before the return of your stateless component, like so :
`javascript
this.form = new Form();
`
Form take an object as arguments, with few mandatories things :
- The name of your form;
- The inputs your want to put inside;
- A callback to invoke on submitting;
A very basic form would look like this :
`javascript
this.form = new Form({
name: 'form', // Must be a string
inputs: [ // Must be an array
new TextInput("name", "Name")
],
submitCbk // Respect the name convention otherwise it won't work
});
`
We will come back later on the Input constructor.
Once you've wrote your callback, you can render your form in two different ways :
- First, you can use our Beautify class, it's gonna make a simple grid system based on Bootstrap. To do so :
`javascript
DefaultTemplate.form(this.form);
`
This method is gonna loop through all the inputs you've declared.
- Second, you will manually render them one by one. This method offer a finer control on the inputs and the way to render them. To do so, you first have to get your input from the Form :
`javascript
this.form.getInput('name');
`
You now have access to all the inner methods of the inputs. To keep it simple for now, let's just get the field, the label and the component to render in case of errors.
`javascript
this.form.getInput('name').getLabel();
this.form.getInput('name').getField();
this.form.getInput('name').getError();
`
As they are all different React components, you can place them as your desires inside your HTML, inside Bootsrap cards for example.
Obviously, as we have never tell to the Form how to validate our inputs, the error component is never gonna render.
Create your inputs
The previous example lead us to the next step, configuring our inputs. Every inputs take two mandatories parameters : his name, and his label name just like we did before.
But you can pass an extra parameter that we call the validators.
`javascript
new TextInput("name", "Name", [Required]);
`
The validators goal is too ensure your data is the one you're expecting every time your gonna submit.
The 'Required' validator is also imported from the library. This one will ensure that the field must be fulfilled by at least one character to pass the submission process.
Note that even if you give one validator, this one must be in an array.
Every time you'll submit your form, we'll loop through all the validators for every inputs, and check if they pass the test we wrote for it.
Submit your form
To help you submitting your form, we expose a method inside the Form you just created, submit().
It's your job to create the button, or whatever you want to trigger the submit.
`javascript
this.form.submit();
`
Extra parameters for the form constructor
`javascript
this.form = new Form({
name: 'form', // Must be a string
inputs: [ // Must be an array
new TextInput("name", "Name")
],
submitCbk // Respect the name convention otherwise it won't work
});
`
Previously we left our form like this, but it does accept a few more things to make your developpement even easier.
#### data
`javascript
data : {}
`
Passing an object called data will auto complete your inputs with the data contained into the object.
For example :
`javascript
data : {
name : "Jacques"
}
`
Will add the word "Jacques" as a value for the "name" input. You can pass as much data as you want, just pay attention to respect your inputs names for the data keys.
#### changeCbk
`javascript
changeCbk : yourFunction
`
The form accept another function, an onChange function. Wrote it, and do whatever you want inside, that function will be called on every changes for every inputs for the form.
#### blurCbk
`javascript
blurCbk : yourFunction
`
It does accept aswell an onBlur function wich will proc everytime the user will lost the focus on an input.
#### parent
`javascript
parent : this
`
Only use it when you plan on using nested forms, it allow react-forms to notify your component that a new form has been added and need to be rendered.
#### formatting
`javascript
formatting : {
field: yourCustomClass,
fieldError: yourCustomClass,
label: yourCustomClass,
labelError: yourCustomClass,
error : yourCustomClass
}
`
In case you need to overwrite some, or even all, the preformatted styles inside your form you can use the formatting object. We'll see right after how to create a custom class, but for now let's focus on how to use the object.
You NEED to respect the keys spelling, otherwise it won't work. React-forms is made so it does have fallback values for all the keys specified above, if you only want to overwrite one, pass this one, no need to pass them all everytime.
Customize your form
React-form styling is based on classes that we expose to you :
- DefaultFieldFormatting
- DefaultErrorFieldFormatting
- DefaultLabelFormatting
- DefaultErrorLabelFormatting
- DefaultErrorFormatting
All of them contains numerous methods to target specific type of inputs, they all follow that template :
`javascript
static oneOfTheFollowingNames = () => "someClassNames";
`
- defaultClassNames
- text
- password
- number
- select
- radio
- date
- combobox
- file
- multiselect
- range
- time
- timesel
- numeric
- datetime
- email
- tel
- checkbox
Keep in mind that, by default, most of the methods are based on the defaultClassNames result.
To create your own class, create a new file, and create a new class inside who extend the default class you want to overwrite.
Inside of the class, you can choose to overwrite whatever method you want just be recopying it and changing the return value :
`javascript
static text = () => "myTextInputClasses";
`
Then import your custom class inside the component containing your form, and pass it to the formatting object.
Form inner methods
All the following methods can be applied after
`javascript
this.form;
`
-------------------------------------
#### mongo
`javascript
mongo();
`
This method is going to log you in the console what to put inside your persisters for the back-end, you can copy-paste it blindly.
#### joi
`javascript
joi();
`
Same as the method above, it does log you the joi you'll need for your back-end in the console.
#### validate
`javascript
validate();
`
It will check all your inputs and check if they pass the validators you've setted up nor the default ones.
#### clearInputs
`javascript
clearInputs();
`
Will clear all the inputs.
#### getRawData
`javascript
getRawData();
`
Extract all the data from the form at the given time of execution.
#### getInput
`javascript
getInput($input_name);
`
Return the input class, giving access to input properties. (Warn : It's not a React Component, it's a js class).
#### disable/enable
`javascript
disable();
enable();
`
They enable or disable all the inputs inside the form, if they are disabled, no changed are allowed.
$3
#### addSubForm
`javascript
addSubForm($subform);
`
Allow you to add a nested form inside your form (a sub form basically), work recursively so you can add as much as you want, and as deep as you want.
Take care, if you plan on using nested forms, you MUST pass an extra property inside the object constructing your form :
`javascript
parent : this
`
#### removeSubForm
`javascript
removeSubForm($subform_id);
`
Remove that subform, need the subform specific id to be able to find it.
#### getSubForm
`javascript
getSubForm($subform_id);
`
Return the subform. (Warn : Just like getInput(), it does return a js class, not a component) You can apply every form methods to it.
Inputs inner methods.
#### setFieldProperty
`javascript
setFieldProperty($name, $value, [$cbk]);
`
Call this method when you want to manually add/update props passed to the input.
- E.g :
`javascript
this.form.getInput('email').setFieldProperty("placeholder", "Enter your email");
`
This is gonna update this specific input to add the placeholder inside. Keep in mind that the code above will be translated as :
`javascript
placeholder="Enter your email"
`
so don't forget to update your code accordingly if you need to wrap inside an object, for the style property for example.
The callback will be called once the property is set.
#### setLabelProperty / setErrorProperty
`javascript
setLabelProperty($name, $value, [$cbk]);
setErrorProperty($name, $value, [$cbk]);
`
Both do the same as setFieldProperty, but applied respectively to the label, and error components.
#### setFieldValue
`javascript
setFieldValue($value, [$cbk]);
`
Allow you to manually set a value inside the field.
The callback will be called once the update is done.
#### setLabelValue / setErrorValue
Same as above.
#### getFieldValue
`javascript
getFieldValue();
`
Return the current value of that specific field, at the given time of execution.
#### show / hide
`javascript
show();
hide();
`
Apply to the field, label, and error. Will hide or show them, it's the same as applying :
`javascript
hidden=true
`
#### enable / disable
`javascript
enable();
disable();
`
Will disable or enable the field, it's working the same as manually setting the property of the field to disabled true or false.
#### getLabel / getField / getError
`javascript
getLabel();
getField();
getError();
`
As mentionned at the beginning, the methods will return you the React component to put inside your code.
#### invalidate
`javascript
invalidate($errorMessage);
`
Using this allow you to manually invalidate your input. You'll see your error message where you put the component, aswell as the error style appearing around your field and your label.
#### validate
`javascript
validate();
``