DLS
DLS

Reputation: 5491

Entire form being rerendered in React with Redux state

I have dynamic JSON data and have a custom method to go through the JSON to dynamically render a form on the page. The reason for the JSON schema is to build various forms that is not predefined.

I have hooked up Redux so that the schema and the formValues below gets assigned as the props of this class. So, the form is rendering correctly with the correct label, correct input field types etc. When an onChange event happens on the fields, the app state(under formData) is being updated correctly. But I am noticing that when the formData changes in the app state, the entire form gets re-rendered, instead of just the "specific fields". Is this because I am storing the form values as an object under formData like this? How do I avoid this issue?

formData = {
   userName: 'username',
   firstName: 'firstName
}

Example schema

const form =  {
  "fields":[
            {
               "label":"Username",
               "field_type":"text",
               "name":"username"
            },
            {
               "label":"First Name",
               "field_type":"text",
               "name":"firstName"
            }
    ]
  }

Redux state

const reducer = combineReducers({
   formSchema: FormSchema,
   formData: Form
});

//render method

render() {
      const { fields } = this.props.form,
      forms = fields.map(({label, name, field_type, required }) => {
      const value = value; //assume this finds the correct value from the "formData" state.
      return (
        <div key={name}>
          <label>{label}</label>
          <input type={field_type}
            onChange={this.onChange}
            value={value}
            name={name} />
        </div>
      );
    })
}

//onchange method (for controlled form inputs, updates the fields in the formData app state)

onChange(event) {
   this.props.dispatch(updateFormData({
      field: event.target.name,
      value: event.target.value
    }));
}

Upvotes: 1

Views: 1811

Answers (1)

Rom Grk
Rom Grk

Reputation: 536

From your example I'm not sure, but if you're rendering the whole thing in a single render() method, yes, the component will be rendered again. And that is the problem, THE component. If you are trying to have multiple components, then they should be split up as much as possible. Otherwise if the state changes, it triggers a re-render of the only component there is. Try breaking it as much as you can.

Hints: (dont know if they apply but maybe)

  • use ref={}s
  • implement shouldComponentUpdate()

EDIT: Just thought about this, but are you storing the fields' values in your state? This doesnt feel correct. Be sure to read carefully the React guide about controlled components. (Eg try to render using plain <span>s instead of inputs, and listen to onKeyPress. Would it still work? If not you might be misusing the value attribute)

Upvotes: 1

Related Questions