Handling Form Inputs in a controlled manner
Tags: react, javascript, es6, frontend
Published: 2018-07-04 22:53:55

---
title: Handling Form Inputs in a controlled manner
published: true
description: In this introductory article, we will look at how to handle form input state in a controlled manner. In HTML, form elements like <input> and <select>, ordinarily maintain and subsequently update their state based on user input in an uncontrolled manner. However, React provides a single state store for dealing with state updates (via the setState() API). Therefore, it is best to harness this API for dealing with state updates, so as to only handle updates/changes in a single place. Of course, this will give us total control and allow us quickly track down bugs. 
tags: #ReactJS #JavaScript #ES6 #Front-end
---

![A sample registration form](https://thepracticaldev.s3.amazonaws.com/i/xs6nywaxcpy35c8frvh3.png)


[__React__](https://www.reactjs.org) advocates for a single source of truth when it comes to handling state or data changes. In __HTML__, form elements like `__input__` and `__textarea__` maintain and update their __state__ based on user input in an uncontrolled fashion. However, since React provides __a single state store__ for dealing with state updates (via the setState() API), it is best we look at a better way of handling form state in a controlled way - so as to ensure consistency in dealing with state updates all in one place. Of course, the benefits of this as a developer is that it will give you total control over your form input state and allow you to quickly know where a bug is originating from.  

In this tutorial, we will learn how to handle and keep track of the values entered when a user types into a form __input__ or __textarea__ field. So here, will be looking at a simple case of handling state updates in React. 

Note that, a React state is just a __simple Javascript object__ - which we declare like so
 
```
  state = {};

```

Also, it is advisable not to tamper or mutate this state object directly, but only via the __setState__ method [which we will be looking at later on]. 


Aside: The React team at Facebook has provided a boilerplate for quickly building and bootstrapping React applications. __Create-react-app__ is a tool that helps to quickly bootstrap React applications, so as to get up and running in little time and avoid the complexities involved in dealing with the entire initial setup process. For more on this, please consult the documentation on, [Create React App](https://facebook.github.io/create-react-app/). Additionally, for quick prototyping and demos, React also works with just an HTML file and some script tags, without the need for a large setup or installation steps. For more information on this, please do well to check how to [add a React component to an HTML page](https://reactjs.org/docs/add-react-to-a-website.html). 

Now to begin, we create a __stateful__ React Component - this is necessary because we intend to handle state updates for our form input field. To write a stateful component, we use the eS6 class syntax outlined below;

```
class App extends React.Component {
constructor(...args) {
  super();
  this.state = {
    value: '', 
  }
  this.onHandleChange = this.onHandleChange.bind(this);
}

```
Discussion: Here, our App class is extending or inheriting the capabilities of the React component API, which allows us to use declare a constructor function where we can then declare our initial state object. ES6 improves ___class inheritance___ with __extends__ keyword. __super__ lets us refer to the parent object constructor/class, in this case, the React component. This then allows us to set our component state and bind our component methods to the component class. The state object contains a value property which is initially set to an empty string. 

Next, we implement our component method;

```
onHandleChange (e) {
  console.log(e.target.value); //logs the user event to the console
  this.setState({ value: e.target.value
  })
}

```

Note that, we can also declare component methods using the new es6 fat arrow functions, and avoid the need of binding our class methods to the constructor function. This is because arrow functions have their own *this* context. To avoid us from delving too much, you can check out how to use arrow functions [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

Discussion:- Here, the *onHandleChange* component method provides a way for us to be able to update the state value of our input field using the *setState* method we mentioned earlier. We can also see that we are updating the state of our value based on the user event on the form input field. Additionally, and like we previously mentioned, the __setState__ method is the only advisable way for dealing with state updates in a React component, instead of directly mutating or changing `this.state.value`.

Next, we call the render method, which returns the JSX to be rendered in the browser. 

```
render (){
  return (
    <div>
      <h1>A Simple Form Input Example</h1>
      <input type = 'text'  onChange = {this.onHandleChange} value = {this.state.value}/>   
    </div>
  );
}
}

``` 

Discussion: Here, the input field contains a *type* of *text*. An *onChange* attribute which helps to __bind__ the component method to the input field so that update to the state is carried out; and then finally a *value* attribute that makes the input field a React specific state-controlled field.

Finally, we render our app class component to the DOM. We do so by calling the __ReactDOM.render__ method with the component class and the id of the target element in our HTML file like so;

```
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

```

If you are interested, you can check the link to this article [here](https://codesandbox.io/s/7m53wv27p6) to get a feel of how it works. Please, don't hesitate to drop your likes, questions, and comments. 

Thanks for reading. Until next time. :)