React Form With Lot Of Children, Parent State
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
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.
Related Questions
- → How do I create an array from a single form input box with php on octobercms?
- → Setting a default value on settings form return null in Octobercms
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → How to handle Token Mismatch Exception
- → How to unit test forms with Sinon and Chai
- → Insert values from FORM to DB using AJAX on october cmd
- → October cms, plugin, forms that accepts input from user in front-end of the web
- → Adding html data attribute to simple_forms input
- → Do something before form submit
- → Insert data into 2 different tables from a single form using OctoberCMS Builder Plugin
- → Using ReactJs, How do I update my form fields when my parent object sent in from props changes?
- → Make default attribute for Model in October CMS
- → OctoberCMS plugin form database relationships