Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to create form in ReactJS

Introduction

ReactJS, often simply called React, is a robust JavaScript library that empowers developers to build user interfaces, primarily for single-page applications. If you're new to programming or just getting started with React, one of the most common tasks you'll likely encounter is creating forms. This blog will guide you through the process in a beginner-friendly way, with plenty of code examples and clear explanations.

Understanding React

Before we dive into creating forms, it's important to understand what React is and what it does. Think of React as a tool that helps you create and manage the different parts of your web application, which we call components. A component can be a button, a form, a menu, or anything else that the user interacts with on the screen. React helps us manage and reuse these components efficiently, making our lives as developers easier.

What is a Form?

In web development, a form is a component that allows users to input data that is sent to a server for processing. For example, when you sign up for a new account on a website, you typically fill out a form with your name, email address, password, etc. That information is then sent to the server where it is processed, and your new account is created.

Setting Up Your Development Environment

To start building our form in React, we first need to set up our development environment. This requires having Node.js and NPM (Node Package Manager) installed on your computer. Node.js is a JavaScript runtime that lets you run JavaScript on your computer, while NPM is a tool that comes with Node.js and helps you manage JavaScript packages.

You can download Node.js and NPM from their official website. Once installed, you can verify their installation by opening your terminal or command prompt and running the following commands:

node -v
npm -v

The commands should print the versions of Node.js and NPM you installed.

Creating a New React App

Next, we need to create a new React application. We can do this easily using the create-react-app command, which sets up a new React application with a basic file structure and some default settings. Run the following command to create a new React app:

npx create-react-app form-app

Replace form-app with the name you want for your application. Once the process is complete, navigate into your new project folder using the cd command:

cd form-app

Creating a Form in React

Now that our environment is set up, we can start building our form. In React, we typically build forms as components. Let's create a new component called Form.

In your project folder, create a new file under the src directory and name it Form.js. This file will house our Form component. Open the Form.js file and start by importing React:

import React from 'react';

Next, let's create our Form component. In this component, we'll use the render() method to define what the component should output:

class Form extends React.Component {
  render() {
    return (
      <form>
        <label>
          Name:
          <input type="text" name="name" />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default Form;

In the code above, our Form component is outputting a basic HTML form with a single text input for the user's name and a submit button.

Managing Form State

In React, we use something called "state" to manage data that can change over time. In the case of our form, the data that changes over time is the user's input. We need to set up our form so that every time the user types something into the input field, we save that input in the state.

To do this, we'll first define a constructor() method in our Form component. This method is where we define our initial state:

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: ''};
  }
// rest of the code
}

Next, we'll set up our input field to call a method every time it changes. We'll call this method handleInputChange:

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: ''};

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    this.setState({name: event.target.value});
  }

  render() {
    return (
      <form>
        <label>
          Name:
          <input type="text" name="name" value={this.state.name} onChange={this.handleInputChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default Form;

In the code above, we're setting the value of the input field to this.state.name and calling this.handleInputChange every time the input field changes.

Handling Form Submission

The final step is to handle form submission. We want to prevent the default form submission event, which refreshes the page, and instead just log the form data to the console. To do this, we'll add a handleSubmit method to our Form component:

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: ''};

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleInputChange(event) {
    this.setState({name: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.name);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" name="name" value={this.state.name} onChange={this.handleInputChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default Form;

In the code above, we're calling this.handleSubmit when the form is submitted. This method prevents the default form submission event and then logs the form data to the console.

Conclusion

And that's it! You've now created your first form in React. This is just the beginning, as there are many more advanced topics to explore in React form handling, such as handling multiple input fields, validation, and more. But hopefully, this guide has given you a good introduction to the basics.

Remember, the best way to learn is by doing. So, try creating different types of forms, experimenting with different types of input fields, and handling form data in various ways. With practice, you'll become a proficient React developer in no time. Happy coding!