Working with Uncontrolled Components in React using useRef hook
As seen earlier, controlled forms are ones whose elements are controlled by React and whose states are controlled in react.
There could be scenarios where you might be integrating third party plugins or libraries which are non-react and you might have to get the input values.
React provides a way to do so, where we can access values on uncontrolled elements using a hook called as useRef.
Similar to useState, useRef also preserves values. Only difference is that useState triggers re-render where useRef doesnot.
useRef indirectly provides element handle to work with it. Unlike controlled components, there is no need to implement onChange for every input type.
With useRef, you need to use the button type as submit in a form.
We will extend our previous example of controlled form to add few uncontrolled elements.
We will add Age input field of type number, Remember Me as a checkbox and select list for title value. Out of above, Age and Remember Me will be uncontrolled inputs.
Selects work similar to any input value. Instead of using selected attribute, in React we can use value attribute to set/get the default value.
Also, in case of checkboxes, we can continue to use the "checked" property to get the value.
For radio buttons, we can use the similar technique, where name remains same but value differs. We can leverage onChange event for them as well.
Using refContainer
Similar to useState, we create ref container for every uncontrolled component.
Setup
Once declared, we need to assign them to the respective HTML element. If we are using refContainer, there is no need of onChange.
Comments
Post a Comment