Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React.js | Uncontrolled Vs Controlled Inputs #3

Open
MauricioAires opened this issue Feb 12, 2023 · 0 comments
Open

React.js | Uncontrolled Vs Controlled Inputs #3

MauricioAires opened this issue Feb 12, 2023 · 0 comments

Comments

@MauricioAires
Copy link
Owner

In HTML, form elements such as , <textarea>, , etc typically maintain their own state and update it based on user input. In React, a mutable (changeable) state is usually kept in the state property of components. In React forms input value can be of two types according to your choice: uncontrolled and controlled values. Uncontrolled input: With uncontrolled input values, there is no updating or changing of any states. It maintains its own internal state, which basically means it remembers what you typed in the field. That value can be exploited by pulling it using the ref keyword whenever it needs to be used. In uncontrolled inputs, the value you submit is the value you get. Controlled input: In controlled inputs, there is at all times some sort of changes and amendments going on in the field, every single character entered and even something like a backspace would count as a change. The current value of the input field will be a prop of the class component (usually it will live in the state referred to by using this.state.varName.) as they don’t maintain their internal state. There will also be a callback function (like onChange, onClick, etc) that is necessary to handle the changes (in value) occurring in the input field, which makes them controllable. Now, Open your react project and edit the NameForm.js file in the src folder: src NameForm.js: Which one is better? It’s evident that controlled and uncontrolled form fields each have their individual benefits. You might need to use both or either depending on what the situation calls for. If you are making a simple form with little to no UI feedback and no need for instant validation (which means you only would validate and/or need the values when you submit), using uncontrolled inputs with refs is what you should go for. It would keep the source of truth in the DOM making it quicker and requiring lesser code. If you need more UI feedback and take into account every little change in the particular input field go for controlled input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant