In HTML, form elements such as <input>, <textarea>, <select>, etc typically maintain their own state and update it based on user input. In React, 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.
Output: Hello Tanisha (Display on alert box)
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 make them controllable.
Output: Tanisha (Displaying on the screen letter by letter as the user types)
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 none 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.
- How to compare password and confirm password inputs using express-validator ?
- ReactJS | Refs
- ReactJS | Fragments
- ReactJS | Using Babel
- ReactJS | Virtual DOM
- ReactJS | Icons
- ReactJS | Router
- EmberJS vs ReactJS
- ReactJS | forms
- ReactJS | AJAX and API
- Difference between ReactJS and Vue.js
- ReactJS | Props - Set 2
- ReactJS | Components
- ReactJS | Introduction to JSX
- ReactJS | Props - Set 1
- ReactJS | Components - Set 2
- ReactJS | PropTypes
- ReactJS | ReactDOM
- ReactJS | Lists
- ReactJS | Keys