blog

  • Home
  • blog
  • React Quickly: How to Work with Forms in React

React Quickly: How to Work with Forms in React

How to Work with Forms in React is an excerpt from React Quickly, a hands-on book by Azat Mardan for anyone who wants to learn React.js fast.

This article covers how to capture text input and input via other form elements like input, textarea, and option. Working with them is paramount to web development, because they allow our applications to receive data (e.g. text) and actions (e.g. clicks) from users.

The source code for the examples in this article is in the ch07 folder of the GitHub repository azat-co/react-quickly. Some demos can be found at http://reactquickly.co/demos.

If you enjoy this post, you might also like to watch our course Build React Forms with Redux.

Recommended Way of Working with Forms in React

In regular HTML, when we work with an input element, the page’s DOM maintains that element’s value in its DOM node. It’s possible to access the value via methods like document.getElementById('email').value, or by using jQuery methods. The DOM is our storage.

In React, when working with forms or any other user input fields, such as standalone text fields or buttons, developers have an interesting problem to solve. From React’s documentation:

React components must represent the state of the view at any point in time and not only at initialization time.

React is all about keeping things simple by using declarative styles to describe UIs. React describes the UI, its end stage, and how it should look.

Can you spot a conflict? In the traditional HTML form elements, the state of the elements will change with the user input. React uses a declarative approach to describe the UI. The input needs to be dynamic to reflect the state properly.

If developers opt not to maintain the component state (in JavaScript), or not to sync it with the view, then it adds problems: there might be a situation when internal state and view are different. React won’t know about changed state. This can lead to all sorts of trouble, and mitigates the simple philosophy of React. The best practice is to keep React’s render() as close to the real DOM as possible, and that includes the data in the form elements.

Consider this example of a text input field. React must include the new value in its render() for that component. Consequently, we need to set the value for our element to new value using value. If we implement an <input> field as we always did it in HTML, React will keep the render() in sync with the real DOM. React won’t allow users to change the value. Try it yourself. It drives me nuts, but it’s the appropriate behavior for React!

render() {
  return <input type="text" name="title" value="Mr." />
}

The code above represents the view at any state, and the value will always be “Mr.”. With input fields, they must change in response to the user keystrokes. Given these points, let’s make the value dynamic.

This is a better implementation, because it’ll be updated from the state:

render() {
  return <input type="text" name="title" value={this.state.title} />
}

What is the value of state? React can’t know about users typing in the form elements. Developers need to implement an event handler to capture changes with onChange.

handleChange(event) {
  this.setState({title: event.target.value})
}
render() {
  return <input type="text" name="title" value={this.state.title} onChange={this.handleChange.bind(this)}/>
}

Given these points, the best practice is for developers to implement the following things to sync the internal state with the view (Figure 1):

  1. define elements in render() using values from state
  2. capture changes of a form element using onChange() as they happen
  3. update the internal state in event handler
  4. save new values in state and then update the view with a new render()
Forms in React, Figure 1: Capturing changes in input and applying to state

Figure 1: Capturing changes in input and applying to state

It might seem like a lot of work at first glance, but I hope that by using React more, you’ll appreciate this approach. It’s called a one-way binding, because state only changes views. There’s no trip back, only a one-way trip from state to view. With one-way binding, a library won’t update state (or model) automatically. One of the main benefits of one-way binding is that it removes complexity when working with large apps where many views can implicitly update many states (data models) and vice versa—Figure 2.

Simple doesn’t always mean less code. Sometimes, like in this case, developers must write extra code to manually set the data from event handlers to the state (which is rendered to view), but this approach tends to be superior when it comes to complex user interfaces and single-page applications with a myriad of views and states. To put it concisely: simple isn’t always easy.

Forms in React, Figure 2: One-way vs two-way binding

Figure 2: One-way vs two-way binding

Conversely, a two-way binding allows views to change states automatically without developers explicitly implementing it. The two-way binding is how Angular 1 works. Interestingly, Angular 2 borrowed the concept of one-way binding from React and made it the default (you can still have two-way binding explicitly).

[affiliate-section title=”Recommended Courses”][affiliate-card title=”Job-Ready Angular and TypeScript Training” affiliatename=”Todd Motto” text=”The ultimate resource to learn Angular and its ecosystem. Use coupon code ‘SITEPOINT’ at checkout to get 25% off.” url=”https://ultimateangular.com/” imageurl=”https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2017/08/1502370007todd.png”][/affiliate-section]

For this reason, we’ll cover the recommended approach of working with forms first. It’s called controlled components and it ensures that the internal component state is always in sync with the view. The alternative approach is uncontrolled component.

So far, we’ve learned the best practice for working with input fields in React, which is to capture the change and apply it to state as depicted in Figure 1 (input to changed view). Next, let’s look at how we define a form and its elements.

Continue reading %React Quickly: How to Work with Forms in React%

LEAVE A REPLY