Recently, if you read my little weird blogs, you know I learn React.js and build one project. In the project, I made many mistakes like creating a complex component structure. Later I removed all components and made a clear folder structure.
I created cards that did not show data, and I don’t know why. And so on. But one problem came when I used the React-Hook-Forms and my custom input field.
This problem gave me more knowledge as well as an idea about how react-hook-form works. The problem is like this. When I want to access the child component from the parent component to access the data entered by the user.
That gave me undefined instead of the value which was passed by the user. I was not able to find out why that happened. Later I found out that my parent element does not have access to the input field. That is the problem.
Now I don’t know why the parent element does not access the child element. In the parent element, I did not make a mistake in using the child element. Then why did that happen.
Subsequently, I found out that the register which is used for accessing the value from the child element sends one ref to the child element. But I did not define that or use that. Now I found out the method that is used to pass reference to the child component.
React provides a higher order function named forwardRef to solve the problem of passing the reference to the child component. The forwardRef is not needed in a normal input or select field.
The custom component built for reusability blocks the reference. In this situation, we need a service that passes the reference from the parent to the child component.
The service is provided by the higher order function forwardRef. To use forwardRef in the custom component, you need to import it from React. And pass it as a secondary separate parameter ref in the function.
Now pass this parameter as a ref property in the custom input component. And wrap your exported component in forwardRef. Now you have access to the child component in the parent.
And also have the value which is passed in your child component. Now this function solved my problem of passing undefined value.
If I have done something wrong, please let me know in the comments.
Top comments (0)