Controlled Components: In simple HTML elements like input tag, the value of the input field is changed whenever the user type. But, In React, whatever the value user types we save it in state and pass the same value to the input tag as its value, so here its value is not changed by DOM, it is controlled by react state. This may sound complicated But let’s understand with an example.
In the above example, the input element is uncontrolled whatever the value user type is in the DOM. We are logging that value on the console by getting it from the DOM and the method onInputChange will be called any time user type in anything so the value will be printed on the console every time (Ctrl + Shift + F11) google chrome user to open the console.
React is used to handle the value of user enters.
What will happening in the above react example, when we have made inputValue state with value null, and the value of that state is provided to the input field which means whatever the value of the inputValue is we will see it in the input box. And we are updating the value of inputValue each time user changing the value in the input by calling setState() function and dom is re-rendering because we are changing the value of inputValue using setState(). Here, we can easily get the value whatever user type in the input field and pass it to wherever we want from React state. The same happens with other elements like the text area and select. Here is another example that prevents the browser from automatically submitting the form.
Here we just add onSubmit event handler which calls the function onFormSumbit and performs the action of replacing the value of inputValue to ‘Hello World!’, and the preventDefault() function is used to prevent the browser from submitting the form and reloading the page.
- Styling Django Forms with django-crispy-forms
- HTML | DOM forms Collection
- CSS | Styling Forms
- Bootstrap 4 | Custom Forms
- Bootstrap 4 | Forms
- Semantic-UI | Forms
- How to Create a Pre-Filled forms in Node.js ?
- How to embed Google Forms on any Website ?
- How to embed Google Forms in New Google Sites ?
- ReactJS | Introduction to JSX
- ReactJS | ReactDOM
- ReactJS | Rendering Elements
- ReactJS | Components
- ReactJS | Components - Set 2
- ReactJS | State in React
- ReactJS | Lifecycle of Components
- ReactJS | Props - Set 1
- ReactJS | Implementing State & Lifecycle
- ReactJS | Props - Set 2
- ReactJS | PropTypes
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.