Extracting Deeply Nested Child Form Field Data or Save it to Redux

Hi everyone,

I am creating a Form which has some reusable input fields. I have extracted the fields into their own components. But now I have several such components and upon submit I need to post the data from these nested components to an action. Not only that but I also want to be able to show an error beneath each of these fields when I post the Data. Sorry that I dont have the code handy but I can explain this through the help of the following depiction,


- Container Component 
-- Form Component A (Contains the submission click handler)
--- InputFieldTypeA Component1
--- InputFieldTypeB Component1
--- ...
--- InputFieldTypeA Component2
--- InputFieldTypeB Component2
--- ...
--- InputFieldTypeA Component3
--- InputFieldTypeB Component3
---

I know I can create a ref and upon a click of a submit, I can use the ref to extract all the fields from each component. Another way would be to store form data in Redux. However I am not sure which one is the best practice or an industry standard when it comes to storing form data and how do you go about showing error messages? How can we reduce the lengthy leg work of pulling the data from each component, validate it and then show validation errors? Is there a way to automate this process?

Thanks.

I would keep the form as a controlled component and store the value in the Container component with the useState hook:

If you have decided that you need Redux for the project then upon submit you could send the data to the store. There are some good hooks in React Redux package (useSelector for getting data and useDispatch for sending data to store) that make it easier.

I am pretty new to Redux but a lot of the logic will depend on what you later plan to do with the data. For example, send it to an API…

How will you submit the data of nested components directly to redux upon the higher level components submit button through useSelector or through the other hooks?

This tutorial shows how you can do it. It builds a basic social media app and uses forms. Scroll down to Adding New Posts and you will see how useState is used for storing form-data in the components state. Then there is a Save Post button that will use useDispatch to send data to store. If you have subcomponents in the form then you can store state for those in the parent component before dispatch to store (when button is clicked).

Redux Essentials Tutorial - Data flow