Besart Marku
Besart Marku

Reputation: 543

Need some suggestions for a dynamic form using React

I'm building an enterprise-level application and I need some tips and suggestions for handling dynamic form.

The fields of the form are totally dynamic and they come differently for each user. I loop through each field(fields come from an API call) on a file called renderUiType.js and based on a property of the field called uitype, we render different Inputs. For example if uitype===1{render TextField}, if uitype===2{ render Checkbox } and so on...

So far the displaying part is correct but now I want to save the values of each field rendered and have them all in an object so I can do a POST API Call

So my question is, how can I do that? Should I create an onChange handler function for each form-element at the main file renderUiType.js and then pass it with props to the form-elements components or should I use Redux?

Any suggestion/article or anything is welcomed. Thank you

The folder structure looks like the image below(just in case it helps to understand what I ask)

..enter image description here

Upvotes: 0

Views: 681

Answers (2)

Maciej Trojniarz
Maciej Trojniarz

Reputation: 722

You can use one callback function and use it in each onChange component specific handlers. You could have everything in state of the Form if you would like hidden under the unique keys/id, so you don't need to have Redux. f.e.

if (uitype===1)
{render <TextField  value={this.state[fieldId]} onChange={this.onChange}/>}
if (uitype===2)
{ render <Checkbox value={this.state[fieldId]} onChange={this.onChange}/>}

or to simplify:

const getComponentByUIType = (uiType) => {
  switch(uiType) {
    case 1: return TextField
    case 2: return Checkbox
  }
}
// ...
onChange = fieldId => value => this.setState(state => ({fieldId: value}))
//...
render() {
   getComponentByUIType(uiType).map(Component => <Component value={this.state[fieldId]} onChange = {this.onChange(fieldId)} />
}

Upvotes: 1

Raicuparta
Raicuparta

Reputation: 2115

Using Redux for this shouldn't be necessary unless you need to access this form's state somewhere outside the form. If you only need the form info to do a POST, I would keep all the data inside one component's state.

Just use the unique ID provided by the IP (the one you were gonna use for the POST) to build that state object. Every field will have an onChange that updates the main form component's state, and then that same value from the state is passed in to each field as a prop.

Upvotes: 1

Related Questions