Using Ref in React in 2 ways
Today, I'm going to talk about 2 ways to pass Ref from parent to child in React.
If you want to maintain the project well in the long run, you always want to do reusable and readable components. With these approaches, you will achieve it in many use cases.
Most beginner developers create giant components encapsulating everything in one component, creating poorly maintainable projects. With these approaches, you can create reusable components when Ref using is needed.
Passing Ref from parent to child properly in 2 ways
Here they are:
- Passing Ref from parent to child as a prop
- Passing Ref from parent to child with forwardRef
Let's dive into them!
Passing Ref from parent to child as a prop
In this case, we use the inputRef property to pass the ref of the Form component to the CustomInput.
In this way, we have control of the input reference from the parent, and in the child component, we have the component with the extracted logic and styles.
Passing Ref from parent to child with forwardRef
In this case, if we want to pass the ref directly with the ref property, we must use forwardRef, as seen in the image above.
Conclusion
Passing Ref from parent to child is crucial for avoiding doing one giant component with everything.
In the example above, you will extract that input into an independent component to be reused across multiple forms.
You will make your React components more reusable using one of the 2 ways when needed in your projects.
Here are 2 helpful resources from the official React documentation about the topic:
https://react.dev/reference/react/useRef
https://react.dev/reference/react/forwardRef
I strongly recommend them.
I hope you enjoyed the article.
If you have any questions, feel free to contact me on LinkedIn, Edi Rodriguez, or leave a comment in the post.
See you in the next post.
Have a great day!
If you want to continue learning front-end development, here is the entire collection of articles from the newsletter:
https://www.saturdayfrontend.com
You will find many topics that may interest you there.