Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 9, 2022 05:09 pm GMT

Controlled Forms - Why do we need them?

With learning react over the past three weeks, there was a lot of discussion about controlled forms vs. uncontrolled forms, and a big emphasis on why we should use controlled components instead. Let's first break down exactly what the difference is between the two..

Forms -

Traditionally forms store & maintain their own state, and it will get updated when you query the DOM and pull the current value. React takes a different approach by taking the current value through props, storing the values to state inside the component, and monitoring any changes through the onChange callback. The main difference is that a controlled component is all handled completely by react. Take a look and this screenshot of what a controlled form looks like, the key indicators are having the input value set to the state, and having an onChange attribute on the input as well.

Image description

notice we attached the onChange callback to the input, and every time there is a change on the input it is triggering a helper function, which will be taking in that value and setting it to state, which is either declared inside the component or passed down from a parent component. We then take the value= attribute and assign our state to it. So now every time a change happens, it updates state, which is then assigned back to the value of the form in almost this looping type of way. This is what truly makes a controlled form, everything is handled within react and not pulled from the DOM.

There is very little reason to ever choose an uncontrolled form compared to a controlled one, in most cases you will always want it to be controlled with React. It allows you to have more flexibility with managing state inside the components, you can also have several inputs for one piece of data, and also allows you to have dynamic inputs as well.

If you are interested in learning more about controlled forms take a look at the documentation from react.js.


Original Link: https://dev.to/keffdu/controlled-forms-why-do-we-need-them-5g23

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To