DEV Community

Alexander Nnakwue
Alexander Nnakwue

Posted on • Updated on

Handling Form Inputs in a controlled manner

A sample registration form

React 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. 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.

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

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 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. :)

Top comments (0)