~/reactjs/reactjs-basic-form-handling-form-submission.md

ReactJS - Basic Form Handling and Form submission

3 min readJune 27, 2020by Gorav Singal#reactjs
// TL;DR

Handle React forms by storing input values in component state via onChange handlers, preventing default form submission with preventDefault, and reading state on submit.

ReactJS - Basic Form Handling and Form submission

Introduction

Lets take a look at how forms are being handled in ReactJS. We will have a very basic form having following fields:

  • First Name
  • Last Name
  • Full Name

On submit, we would just want to show the full name field. We will see:

  • How to handle change events
  • How to capture value of eaach field in state
  • How to handle submit button event
  • How to not re-render the form

Form Component - Basic Form Handling

import React, {Component} from 'react';

class Form extends Component {
    state = {
        firstName: "",
        lastName: "",
        fullName: ""
    };

    handleChange = (event) => {
        this.setState({
            [event.target.name]: event.target.value
        });
    }
    handleSubmit = (event) => {
        event.preventDefault();
        this.setState({
            fullName: `${this.state.firstName} ${this.state.lastName}`,
            firstName: "",
            lastName: ""
        });
    }
    render() {
        return (
            <section>
                <article>
                    <form onSubmit={this.handleSubmit}>
                        <input
                        type="text"
                        name="firstName"
                        value={this.state.firstName}
                        onChange={this.handleChange}
                        />
                        <input
                        type="text"
                        name="lastName"
                        value={this.state.lastName}
                        onChange={this.handleChange}
                        />
                        <button type="submit">submit</button>
                    </form>
                </article>
                <article>
                    <h1>Full Name</h1>
                    <div>{this.state.fullName}</div>
                </article>
            </section>
        )
    }
}


class App extends Component {
    render() {
        return <React.Fragment>
            <Form />
        </React.Fragment>
    }
}

export default App;

In above form code, lets discuss various concepts:

  • We have two text fields for first and last name
  • configured a change event handler. Whenever we type something on these text boxes, onChange event will trigger and we will save the value in state of component.
  • You see the one liner code in handleChange:
[event.target.name]: event.target.value

This is a shorthand code to set the required field. If its not there, we would be doing set of if-else. And, checking if name is firstName of lastName. Something like:

if (event.target.name === "firstName") {
   const textValue = event.target.value;

   this.setState({
     firstName: textValue
   });
}

This is not at all required.

  • Finally, handleSubmit is the method to handle submission of form.
  • We have used:
event.preventDefault();

This is to prevent the default behavior of submission. If its not there, entire component will re-rendered. This will cause the reset of our state.

  • Next, we are just setting fullName field in the state and clearing firstName and lastName.

This is a very basic form handling, and the objective is to give an idea of how the forms are handled.

Form Handling - Getting value using Ref

Another way to get values of input fields is by using keyword ref. And, we can even set styles on the input items.

Lets take a look at the example:

import React, { Component } from "react";

class Form extends Component {
  handleSubmit = e => {
    e.preventDefault();

    // accessing field from refs
    const nameField = this.refs.nameField;
    const nameFieldValue = nameField.value;

    // accessing field by class's member variable
    const email = this.email.value;

    const infoText = this.refs.infoText;
    const infoTextValue = infoText.textContent;
    infoText.style.color = "red";
    console.log(nameFieldValue, email, infoTextValue);
  };
  render() {
    return (
      <section>
        <form onSubmit={this.handleSubmit}>
          <input type="text" ref="nameField" />
          <input type="email" ref={ev => (this.email = ev)} />
          <button type="submit">submit</button>
        </form>
        <p ref="infoText">hello world</p>
      </section>
    );
  }
}

class App extends Component {
  render() {
    return <Form />;
  }
}

export default App;

You can see an interesting concept of getting values by using refs. For this, you need to give a ref value in input field and you can access them in any function of this component.

Another new thing we see is:

<input type="email" ref={ev => (this.email = ev)} />

Here, we are declaring a method in ref. And, we are setting the value into a variable email, which is class’s member variable. And, we can access class’s member variable anywhere in the class.

Another example of getting the p item and setting some color style on it.

const infoText = this.refs.infoText;
const infoTextValue = infoText.textContent;
infoText.style.color = "red";

To get the innerContent of this p field. We can use:

const infoText = this.refs.infoText;
const infoTextValue = infoText.textContent;
// get the value in <p> field.

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS - Understanding SetState Asynchronous Behavior and How to correctly use it

ReactJS setState is Asynchronous setState() method in ReactJS class components…

ReactJS - How to restrict data type for different kind of data

ReactJS - How to restrict data type for different kind of data

Introduction Javascript is not a strict type language. We can use a variable to…

ReactJS - How to create ReactJS components

ReactJS - How to create ReactJS components

Introduction In this post, we will talk about basic of how to create components…

ReactJS - How to pass method to component and how to pass arguments to method

ReactJS - How to pass method to component and how to pass arguments to method

Introduction In the ReactJS project, you are having aa parent component and a…

ReactJS - 3 ways to Import components in ReactJS

ReactJS - 3 ways to Import components in ReactJS

Introduction In this post, we will discuss 3 different ways to import a…

ReactJS - How to use conditionals in render JSX

ReactJS - How to use conditionals in render JSX

Introduction In this post, I will show several ways to use conditionals while…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…