This is one of many components that tries to solve the form input problems of React. As I tried many diffent solutions I found that all of them try to enforce a certain layout. I want a solution that just provides an easy way to fix the binding of data to input components without any interferance in the way I do my layout.
This component provides a simple way of displaying an input form and automatic binding of data. All you have to do is to provide the data, one or more schema's.
An optional feature is the formatting of data. Per field you can configure if you want to format the data value into an input value and if you want to format the entered value into a data value.
For example: Suppose your data structure contains a date field. You do want to format this value into a locale date format and format the entered value back into a date value.
An other optional feature is date validation. You can provide a function that validates a value. This is a per field configuration.
If a field fails, the css class of the field can be changed based on the validation.
If a schema fails, the css class of the schema can be changed based on the validation.
If a form fails, the css class of the schema can be changed based on the validation.
If one validation fails, the form cannot submit.
When the form submits, you receive bunch of information:
- The values (of course)
- The original values
- Per field a boolean that tells if the value changed
- The entered values
- The formatted values
const schema = [
{ id: 'firstname', component: (props) => <Row><Col>Firstname:</Col><Col><input {...props} /></Col><Row>}
{ id: 'lastname', component: (props) => <Row><Col>Lastname:</Col><Col><input {...props} /></Col><Row>}
];
return (
<Form data={myData}>
<Schema schema={schema} />
</Form>
)
const schema1 = [
{ id: 'firstname', component: (props) => <Row><Col>Firstname:</Col><Col><input {...props} /></Col><Row>}
{ id: 'lastname', component: (props) => <Row><Col>Lastname:</Col><Col><input {...props} /></Col><Row>}
];
const schema2 = [
{ id: 'birthdate', component: (props) => <Row><Col>Date of birth:</Col><Col><input {...props} /></Col><Row>}
{ id: 'birthplace', component: (props) => <Row><Col>Place of birth:</Col><Col><input {...props} /></Col><Row>}
];
return (
<Form data={myData}>
<Column>
<Schema schema={schema1} />
</Column>
<Column>
<Schema schema={schema2} />
</Column>
</Form>
)
const ageValidation = age => (age >= 18 && age < 65);
const schema = [
{ id: 'firstname', component: (props) => <Row><Col>Firstname:</Col><Col><input {...props} /></Col><Row>},
{ id: 'lastname', component: (props) => <Row><Col>Lastname:</Col><Col><input {...props} /></Col><Row>},
{ id: 'age', validate: ageValidation, component: (props) => <Row><Col>Age:</Col><Col><input {...props} /></Col><Row>}
];
return (
<Form data={myData}>
<Schema schema={schema} />
</Form>
)