React Extracting Input from a Form

Extracting input from a form refers to the process of collecting and accessing the data users enter into a web form. This data can include various elements like text, numbers, selections, and checkboxes. The extracted data is then used for various purposes,

Retrieving values from HTML input elements in a form is one of the most basic tasks in JavaScript. React.js makes it easy by allowing you to define an object whose attributes are bound against the input elements of a form. This way, an update to the value of an input element will automatically update the value of the object’s attribute that it was bound to.

Binding an Object to a Form

Suppose you have a form that you want to represent information about a single customer, namely a customer’s first name, last name, and status. Each of these attributes is expected to be bound to its own corresponding HTML input element. When the user modifies the value of the input element, the object’s values should also reflect the change.

Defining the Customer Object as a State

You'll first define the customer object as part of a component's state. You can put it in a React component's constructor as you initialize the component's state object. In this case, you'll put in an attribute called customer whose value is an object containing the customer's first name, last name, and status.

import React from 'react';

export default class CustomerForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      customer: {
        firstName: props.firstName,
        lastName: props.lastName,
        status: props.status
      }
    }
  }
}

Notice that the default values of firstName, lastName, and status of the customer object in state are extracted from the component's constructor's props. This will allow another component calling this CustomerForm component to pass some default values. An example of having initial values in props would be if this CustomerForm were rendered with values taken from a database from an AJAX routine to update customer information.

Binding State Values to Input Elements

Now that you have the customer object as part of the state, bind the object's values to the value attribute of your HTML input elements using JSX. This can be found in the component's render() method:

import React from 'react';

export default class CustomerForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      customer: {
        firstName: props.firstName,
        lastName: props.lastName,
        status: props.status
      }
    }
  }

  render() {
    return (
      <div>
        <label>
          First Name: 
        </label>
        <input type="text" value={this.state.customer.firstName}/>
        <br/>
        <label>
          Last Name:
        </label>
        <input type="text" value={this.state.customer.lastName}/>
        <br/>
        <label>
          Status:
        </label>
        <select value={this.state.customer.status}>
          <option value="PENDING">
            Pending
          </option>
          <option value="APPROVED">
            Approved
          </option>
        </select>
      </div>
    );
  }
}

Updating the Customer Object

An event handler function should be supplied for an input element's onChange attribute. This function's signature will accept a single argument, which is an object that contains the reference called target representing the input element itself. The logic of the function can then take the value of the input element and update the state's value (in this case the attributes of the customer object within the component's state).

Example Event Handler Function

Suppose you want to have a function to update the customer's first name. The event handler function will accept an object called event, extract the value of the input element represented by event.target, and update the customer object before updating the component's state with the modified customer object.

handleFirstNameChanged(event) {
  // Extract the current value of the customer from state
  var customer = this.state.customer;

  // Extract the value of the input element represented by `target`
  var modifiedValue = event.target.value;

  // Update the customer object's first name
  customer.firstName = modifiedValue;

  // Update the state object
  this.setState({
    customer: customer
  });
}

Binding Event Handler Function to Input Element

The function above needs to be bound to the input element related to a customer's first name. In JSX, you can have the following:

<label>
  First Name:
</label>
<input type="text" onChange={this.handleFirstNameChanged.bind(this)} />

Binding this

Notice that you had to call .bind(this) to the input element. This will ensure that this, which currently refers to the instance of the component, will remain the same within the function handleFirstNamechanged. Since setState is a method of a react component, the this within the function should always refer to the instance of the React component.

Extracting the Updated Object

To examine the most recent values of the customer object, add a button that when clicked will simply log the object to the console. In an actual app, this is where you would take the object and apply further processing such as submitting it to an API endpoint.

Event Handler Function for Button Click

Our component will have the following event handler function for clicking a button:

handleButtonClicked() {
  console.log(this.state.customer);
}

Binding the Function to the Button

In the JSX, you might have the following HTML snippet and bind the event handler function above its onClick attribute:

<button onClick={this.handleButtonClicked.bind(this}>
  Save Customer
</button>

Final Code

The final code for your CustomerForm component to update all attributes of the customer object will look like the following:

import React from 'react';

export default class CustomerForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      customer: {
        firstName: props.firstName,
        lastName: props.lastName,
        status: props.status
      }
    }
  }

  handleFirstNameChanged(event) {
    var customer        = this.state.customer;
    customer.firstName  = event.target.value;

    this.setState({ customer: customer });
  }

  handleLastNameChanged(event) {
    var customer      = this.state.customer;
    customer.lastName = event.target.value;

    this.setState({ customer: customer });
  }

  handleStatusChanged(event) {
    var customer    = this.state.customer;
    customer.status = event.target.value;

    this.setState({ customer: customer });
  }

  handleButtonClicked() {
    console.log(this.state.customer);
  }

  render() {
    return (
      <div>
        <label>
          First Name: 
        </label>
        <input type="text" value={this.state.customer.firstName} onChange={this.handleFirstNameChanged.bind(this)}/>
        <br/>
        <label>
          Last Name:
        </label>
        <input type="text" value={this.state.customer.lastName} onChange={this.handleLastNameChanged.bind(this)}/>
        <br/>
        <label>
          Status:
        </label>
        <select value={this.state.customer.status} onChange={this.handleStatusChanged.bind(this)}>
          <option value="PENDING">
            Pending
          </option>
          <option value="APPROVED">
            Approved
          </option>
        </select>
        <hr/>
        <button onClick={this.handleButtonClicked.bind(this)}>
          Save Record
        </button>
      </div>
    );
  }
}

This is the end of the guide, wish you successful coding!!!

#react #javascript

2.05 GEEK