Ad

React Form With Lot Of Children, Parent State

- 1 answer

I have a form that is basically a matrix of checkboxes (hundreds) and that has one title text input.

Something in those lines :

render() {
    <form>
        <input type=text>title</input>
        {checkboxes.map(return <cell />)}
    </form>
}

Before, I was saving the global state in the parent, but a single check would take a long time cause the rendering was triggered for every cell.

Now, I have the state (checked true/false) in each cell, so it's faster. I can't really use a function onChecked that lift up the state to the parent cause then I fall back to the same slow pattern.

My question is : how should the parent save the global state (so then I can send it to a server for example) ?

I was thinking of just saving all the data in a variable (in the parent, like this.data) not linked to the state since every children is handling its own state.

Thanks

Ad

Answer

As mentioned in the comments, you should implement the shouldComponentUpdate() method to your Cell component. Something like:

shouldComponentUpdate(nextProps) {
  if(nextProps.checked === this.props.checked) {
    return false;
  }

  return true;
}

This will ensure that re-rendering can never happen if the checked prop hasn't changed since last re-render. You should now be able to keep the state in the parent without any lag.


Alternatively, but not recommended, you could keep the state to each component and add a ref to your <form>. This allows you to utilize some of the helper methods out there that are unique to forms and form-elements.

This could look like:

<form ref={el => this.formRef = el}>
  ...

and

onSubmitToServer() {
  const data = jQuery(this.formRef).serializeArray();
  //do something
}

Obviously, you would need to install and import jQuery for the above to work, or implement your own solution for serializing the array.

Ad
source: stackoverflow.com
Ad