Generating a form
Generating forms based on some data (i.e. JSON) is quite common. You can generate React Advanced Form components, but there is no API exposed for such purpose.

Reasoning

Form shouldn't be concerned with the generation logic. Writing a simple generating function that returns React components (form or fields) is rather simple.
1
import * as fields from './fields'
2
3
/**
4
* Return the generated form based on the provided JSON
5
* that describes the fields of a form.
6
*/
7
function generateForm(props, fieldsJson) {
8
return (
9
<Form {...props}>
10
{generateFields(fieldsJson)}
11
</Form>
12
)
13
}
14
15
function generateFields(fieldsJson) {
16
return fieldsJson.map((fieldParams) => {
17
const { fieldType, ...props } = fieldParams
18
const Field = fields[fieldType]
19
20
return (
21
<Field {...props} />
22
)
23
})
24
}
25
26
export default GeneratedForm extends React.Component {
27
registerUser = ({ serialized }) => {}
28
29
render() {
30
const { fieldsJson } = this.props
31
32
return generateForm({
33
action: this.registerUser,
34
}, fieldsJson)
35
}
36
}
Copied!
The usage of such a component would look as follows:
1
<GeneratedForm
2
fieldsJson={
3
[
4
{
5
fieldType: 'Input',
6
name: 'username',
7
initialValue: '[email protected]',
8
required: true,
9
},
10
{
11
name: 'password',
12
fieldType: 'Select',
13
type: 'password',
14
required: true,
15
},
16
]
17
}
18
/>
Copied!
The contract between your JSON and the generating function is up to you.
Last modified 2yr ago
Copy link
Contents
Reasoning