React Form: 2 Methods to Create and work with

Forms are an integral part of every website. Users interact with the website only through forms. React Form is also responsible for sending data to the server. In websites, all information is sent to the server through forms, which is also true in React. In the following, we will discuss how to create and work with React form.

Read More About React: What is React and why should we use it?

Forms in React, like all other forms, use HTML methods to send data to the server. But the features that React gives us, make it easier. In React, form elements hold the value of internal states. There are two ways to create forms in React.

  1. Using HTML and useState
  2. Using components such as Formik

The difference between HTML form and React form

In the HTML form, the input, textarea, etc values usually store the status entered by the user, but in React, this status is changed by the useState hook.

Create a React JS project

First, we create the React project. To do this, open the VS Code software and go to the desired folder. Then enter the following code in its terminal.

npx create-react-app form

You can enter the name of your project instead of “form”.

Create a form in React JS

react form

After installing the React project, go to the “App.js” file and change the code inside the file as follows.

import React, { useState } from "react";
import "./App.css";

function App() {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");

  const usernameOnChange = (event) => {
    setUsername(event.target.value);
  };

  const passwordOnChange = (event) => {
    setPassword(event.target.value);
  };

  const onSubmitForm = (event) => {
    event.preventDefault();
    alert(username + " - " + password);
  };

  return (
    <form onSubmit={onSubmitForm}>
      <input
        type="text"
        value={username}
        onChange={usernameOnChange}
        placeholder="Enter username"
      />
      <input
        type="password"
        value={password}
        onChange={passwordOnChange}
        placeholder="Enter passwordّ"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default App;

In this method, the HTML and Hook useState codes are used to create and use the form in React. In this example, the username and password are taken from the user and displayed by the alert function.

The difference between forms created by HTML and forms created by React is that the form field data is stored in React. But in HTML forms, field data is deleted each time the page is reloaded. Of course, this also deletes the data in React, but because React is a single page and the page is not reloaded when the data is sent to the server, the form data is preserved.

In this example, each time you enter a value in any of the fields, its onChange function is called and its state status is changed. The user can also view the values while entering a value in the fields.

Remember that in the React form, the input value is always taken from the state.

Add libraries

In this part of creating a form in React, we use useState hook to store form information. So we import the following code.

import React, { useState } from "react";

Send data to the server

As you can see, the form consists of two fields named username and password and Submit button to send data.

<form onSubmit={onSubmitForm}>

In “onSubmit“, we tell the form to call the “onSubmitForm” function after the button is pressed.

const onSubmitForm = (event) => {
    event.preventDefault();
    alert(username + " - " + password);
};

In the “onSubmitForm” function, we prevent data from being sent through the form itself. We used the alert function to display the data, but the data can be sent with the methods of sending data to the server in React.

Of course, you can also write any of the functions such as onChange and onSubmit as below.

<input
    type="text"
    value={username}
    onChange={(e)=>{
        setUsername(e.target.value);
    }}
    placeholder="Enter username"
/>

Each of the implementations is correct and depends on the taste of the programmer.

React form fields

We use the following code to store field data.

const [username, setUsername] = useState("");
const [password, setPassword] = useState("");

The useState hook is used to hold data in React. Through this hook, we can also access the internal functions of React.

<input
    type="text"
    value={username}
    onChange={usernameOnChange}
    placeholder="Enter username"
/>

In this section, the created React form has fields that look like HTML code. In the value section of our data we put the field and in onChange, we specify that if the field value is changed, the usernameOnChange function will be called.

const usernameOnChange = (event) => {
    setUsername(event.target.value);
};

Using the usernameOnChange function, we specify that the input value should be in the username.

Why use useState to create a React form?

We could also write data storage codes like the one below.

let username = "";
const usernameOnChange = (event) => {
    username = event.target.value;
};

We have not used useState in this code and the data transmission operation is done well. One thing to keep in mind is that by using useState we will be able to access React JS internal functions, and in fact, this method replaces this.state.

Validation of form data in React

Like all other forms, the data in React JS must be validated before being sent to the server. To do this, put the following code outside the “App” function.

export const validPassword = new RegExp('^(?=.*?[A-Za-z])(?=.*?[0-9]).{6,}$');

In this validation, we want to check the correctness of the password. So we change the onSubmitForm function as follows.

const onSubmitForm = (event) => {
    event.preventDefault();
    if (validPassword.test(event.target.value)) {
      alert(username + " - " + password);
    } else {
      setPasswordError("Your password is invalid");
    }
};

As you can see, we send the data when the Regex-based password is correct.

After opening with VS Code, enter the following command in the terminal to install the modules.

npm i

Form elements in React JS

Text, number, password and text elements

These types of elements store text. It is true that a number is a type of number, but still, from the point of view of HTML elements, some kind of text goes to you.

<input
    type="text"
    value={username}
    onChange={(e)=>{
        setUsername(e.target.value);
    }}
    placeholder="Enter username"
/>

The only difference is in their type, which you can change to implement a variety of elements. Each element has a type, value, and other items depending on the need that can exist. These element rules follow the HTML element rules. The values of these elements are also the values entered by the user.

textarea

This element, like the previous elements, is textual, but we separated it because two methods can be used to display its value.

<textarea value={textareaValue} onChange={(e)=>{setTextareaValue(e.target.value)}} />

The first method, which is the best method, is written above.

<textarea onChange={(e)=>{setTextareaValue(e.target.value)}} >{textareaValue}</textarea>

But why is the first method the best method? Because in the first method, if we want to programmatically change the value of textarea in React, it is enough to use setTextareaValue. But in the second method, you can not change the value of textarea this way.

radio

This element, like the “radio” element in HTML, is used to select an option from several options.

<input
    type="radio"
    value="Male"
    defaultChecked={true}
    name="gender"
    onChange={(e) => {
        alert(e.target.value);
    }}
/>Male

<input
    type="radio"
    value="Female"
    name="gender"
    onChange={(e) => {
        alert(e.target.value);
    }}
/>Female

The point to keep in mind here is that in React, defaultChecked is used to select a radio by default, not “checked”. Because using “checked” causes technical problems.

checkbox

This element is used for selection by checking. This element is slightly different from “radio” in that we displayed the value or the same value on the radio, but here because there is no value, we will use “checked”.

<input
    type="checkbox"
    name="mail"
    defaultChecked={true}
    onChange={(e) => {
        alert(e.target.checked);
    }}
/>

select

This element is also used to select an option from among the options.

<select
    value={selectValue}
    onChange={(e) => {
        alert(e.target.value);
        setSelectValue(e.target.value);
    }}
    >
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
</select>

Here selectValue uses the useState hook to hold the selected value. But the value attribute is set with this value to display the selected option. In HTML, the selected option is specified with the “selected” attribute.

file

This element is used to upload the file.

Create a React form using Formik

Using the above method can be tedious because for each input we have to write a handler to collect the form data. The Formik component is one of the components that make creating and working with forms in React very easy. So that there is no need to use useState to store data.

Validating the amount of input by the user, monitoring the observed fields, and controlling how the form is registered are some of the things that you can easily control in Formik.

Install Formik

To install Formik, just install it via “npm”.

npm i formik

Use Formik to create forms

Go back to the “App.js” file and import the following code above.

import { Formik, Field, Form } from "formik";

In this code, we will use “Formik”, “Field”, and “Form” itself. The data validation method will be added, which we will discuss in the relevant section.

The following code basically implements how to use Formik in React.

import React from "react";
import { Formik, Field, Form } from "formik";
import "./App.css";

function App() {
  return (
    <Formik
      initialValues={{ username: "", password: "" }}
      onSubmit={(values) => {
        alert("username=" + values.username + " and password=" + values.password);
      }}
    >
      {() => (
        <Form>
          <div>
            <label htmlFor="username">Username</label>
            <Field type="username" name="username" />
          </div>
          <div>
            <label htmlFor="password">Password</label>
            <Field type="password" name="password" />
          </div>
          <div className="">
            <button type="submit">Submit</button>
          </div>
        </Form>
      )}
    </Formik>
  );
}

export default App;

Modify your “App.js” file code as above.

In the initialValues section, we tell Formik what the initial values of the form fields are. This value is more useful in the edit form. In the edit form, the data is received from the server and displayed in the relevant fields for the user to edit.

The onSubmit function is called when you click on the “Submit” button. Data transmission to the server is done in this function, which we only display for simplicity. The data is passed to the onSubmit function via the “values” variable.

In the form rendering section, first put the “Form” tag and write the fields inside it. The “Field” tag has the same function as the input in the above examples, except that it uses Formik to control the inputs.

Validate data in Formik using Yup

We use the Yup component to validate the data. First, we install Yup using the following code.

npm i yup

Then we import it into the file.

import * as Yup from "yup";

To use validation, your form code must look like this:

import React from "react";
import { Formik, Field, Form, ErrorMessage } from "formik";
import * as Yup from "yup";
import "./App.css";

function App() {
  const SchemaLoginForm = Yup.object().shape({
    username: Yup.string().required("Username is required."),
    password: Yup.string()
      .matches(
        /^(?=.*?[A-Za-z])(?=.*?[0-9]).{6,}$/,
        "Password has wrong character."
      )
      .required("Password is required"),
  });

  return (
    <Formik
      validationSchema={SchemaLoginForm}
      initialValues={{ username: "", password: "" }}
      onSubmit={(values) => {
        alert(
          "username=" + values.username + " and password=" + values.password
        );
      }}
    >
      {() => (
        <Form>
          <div>
            <label htmlFor="username">Username</label>
            <Field type="username" name="username" />
            <ErrorMessage name="username">
              {(msg) => <di>{msg}</di>}
            </ErrorMessage>
          </div>
          <div>
            <label htmlFor="password">Password</label>
            <Field type="password" name="password" />
            <ErrorMessage name="password">
              {(msg) => <div>{msg}</div>}
            </ErrorMessage>
          </div>
          <div className="">
            <button type="submit">Submit</button>
          </div>
        </Form>
      )}
    </Formik>
  );
}

export default App;

First of all, we create a schema for validation using Yup, such as the following code.

const SchemaLoginForm = Yup.object().shape({
    username: Yup.string().required("Username is required."),
    password: Yup.string()
      .matches(
        /^(?=.*?[A-Za-z])(?=.*?[0-9]).{6,}$/,
        "Password has wrong character."
      )
      .required("Password is required"),
  });

As you can see, this code specifies how to validate your username and password.

Now we add the validation schema to Formik.

validationSchema={SchemaLoginForm}

For each field that we want to display the validation result, we consider a section called “Error” like the following code.

<label htmlFor="username">Username</label>
<Field type="username" name="username" />
<ErrorMessage name="username">
    {(msg) => <di>{msg}</di>}
</ErrorMessage>

The “msg” variable is defined for Formik. If a value is placed for a variable, it will display it in the corresponding field. In this example, if you click the Submit button without entering your username or password, you will see an error under the username titled “Username is required”. This error is also set for the password.

After opening with VS Code, click the following command to install the modules.

npm i
Shopping Cart