DEV Community

Chinedu Imoh
Chinedu Imoh

Posted on

How To Create a Contact Form in React With KendoReact Form

The KendoReact Form is a fast and small package for form state management built with React and designed with best practices in mind. In this article, we will be going over how to develop a contact form using this React Form component.

The gzipped and minified bundle of the React Form is 5 KB. The component integrates with all KendoReact components and is currently used by the built-in editor of the KendoReact Scheduler. For retrieving its field state, handling component events and rendering custom components, the React Form component uses the following components:

  • KendoReact Field component and FieldRenderProps interface
  • KendoReact FieldArray component and FieldArrayRenderProps interface

Also, when you have to create form layouts, the KendoReact Form library also provides the following components:

In this post, I will demonstrate how to use the KendoReact Form component to build a simple React contact form.

Prerequisites

To follow along with this tutorial, you will need to have:

  • React v16 or newer
  • A basic understanding of React
  • A code editor

React Project Setup

Those who are already familiar with scaffolding a React app using npx can skip ahead because next I will show how to get a React app off the ground for those who aren't.

You need to follow the steps below, and you will get your React app development server running on your local machine. Firstly, enter the following command into your preferred command line interface (CLI), then run the following boilerplate command listed below, provided by React, to help quickly set up a React project for development.

npx create-react-app task-organizer --use-npm
cd task-organizer
npm start
Enter fullscreen mode Exit fullscreen mode

Locate the task-organizer project's directory and open it in your code editor. Now, you can begin by striping down the codes in the App.js file to look like this:

import "./App.css";

function App(){
    return <div classname="app"></div>
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Now that we are done scaffolding our React application, let's begin installing the dependencies for the application.

Dependency Installation

Next, let's add the KendoReact packages we'll be using for this project. I will use the KendoReact Default theme for this project, but other options exist—for example, the KendoReact Bootstrap and the KendoReact Material theme.

Install the KendoReact Default theme by running the following command in the terminal.

npm install --save @progress/kendo-theme-default
Enter fullscreen mode Exit fullscreen mode

Integrating Multiple KendoReact Components

KendoReact is a rich suite of many modular components. In this demonstration, we will use multiple components imported from this React UI library to build the contact form. Below are the dependencies and peer dependencies; run the command to begin the installation.

npm install --save @progress/kendo-react-form @progress/kendo-react-inputs @progress/kendo-react-labels @progress/kendo-drawing @progress/kendo-licensing @progress/kendo-react-intl
Enter fullscreen mode Exit fullscreen mode

I am sure by now you will have noticed the @progress scope we’ve used. The KendoReact library provides many decoupled modules for different purposes; they all scope to @progress (Progress Telerik is the parent company behind KendoReact)—think of it as a global scope for the modules in KendoReact.

Note: KendoReact is a commercial UI component library, and as a part of this, you will need to provide a license key when you use the components in your React projects. You can snag a license key through a free trial or own a commercial license. For more information, you can head over to the KendoReact Licensing page.

Now that all the modules we need are installed, let's begin the development of the contact form.

The React Contact Form

Let's begin by importing all dependencies we will be needing; paste the following code into the App.js file.

import * as React from "react";
import { Form, Field, FormElement } from "@progress/kendo-react-form";
import { Error } from "@progress/kendo-react-labels";
import { Input, TextArea } from "@progress/kendo-react-inputs";
import "@progress/kendo-theme-default";
Enter fullscreen mode Exit fullscreen mode

Above we imported the form, field, formElement from @progress/kendo-react-form, Error from @progress/kendo-react-labels, plus Input and TextArea from @progress/kendo-react-inputs. These are the components that will be used to develop the application. For the imported @progress/kendo-theme-default we added the default styling theme to our component.

Let's move on to writing the EmailInput functionality. Enter the following code below the imports in the App.js file:

const emailValidator = (value) =>
    emailRegex.test(value) ? "" : "Please enter a valid email.";
const EmailInput = (fieldRenderProps) => {
    const { validationMessage, visited, ...others } = fieldRenderProps;
    return (
    <div>
    <Input {...others} />
    {visited && validationMessage && <Error>{validationMessage}</Error>}
    </div>
    );
};
Enter fullscreen mode Exit fullscreen mode

In the code above, we created emailValidator which stores a string that is a conditional set based on the output of emailRegex.test(value). The EmailInput function receives a fieldRenderProps argument and the validationMessage, visited and ...others objects are de-structured from the fieldRenderProps. The EmailInput function also returns a div that contains an input component that receives the remaining objects(..others) and conditional displays the Error Component with a validationMessage.

Now that we are done with that, let's create our App function, which we will render in the browser.

Under the EmailInput function, enter the following code below.

const App = () => {
    const handleSubmit = (dataItem) => alert(JSON.stringify(dataItem, null, 2));
    return (
    <Form
    onSubmit={handleSubmit}
    render={(formRenderProps) => (
    <FormElement
        style={{
        maxWidth: 750,
        margin: "3em auto",
        }}
    >
        <fieldset className={"k-form-fieldset"}>
        <legend className={"k-form-legend"}>Contact Form</legend>
        <div style={{ margin: "1em 0" }}>
        <Field name={"firstName"} component={Input} label={"Email"} />
        </div>
        <div style={{ margin: "1em 0" }}>
        <Field
        name={"lastName"}
        component={EmailInput}
        validator={emailValidator}
        label={"First Name"}
        />
        </div>
        <div style={{ margin: "2em 0" }}>
        <Field
        name={"email"}
        type={"email"}
        component={TextArea}
        label={"Email"}
        />
        </div>
        </fieldset>
        <div className="k-form-buttons">
        <button
        type={"submit"}
        className="k-button k-button-md k-rounded-md k-button-solid k-button-solid-base"
        disabled={!formRenderProps.allowSubmit}
        >
        Submit
        </button>
        </div>
    </FormElement>
    )}
    />
    );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

First, we created a handleSubmit arrow function that receives dataItem as an argument and calls the alerts function with the JSON data containing dataItem, null and 2. But, you can replace this with the REST API you want to use. The App function also returns a Form that uses render props (mainly for cross-cutting concerns) to inject the FormElement as a prop dynamically.

In the FormElement component, there are three fields, which are wrapped by the fieldset. Each field takes in the following props: name, component, label and validator for the email field. The label prop labels the field, while the component props determine if the field is an input, textarea, etc. The name prop is attached to the field data when the form is submitted, then the validator is used by the email field to validate the email.

Here's the complete code of the App.js file.

import * as React from "react";
import { Form, Field, FormElement } from "@progress/kendo-react-form";
import { Error } from "@progress/kendo-react-labels";
import { Input, TextArea } from "@progress/kendo-react-inputs";
import "@progress/kendo-theme-default";
const emailRegex = new RegExp(/\S+@\S+\.\S+/);
const emailValidator = (value) =>
    emailRegex.test(value) ? "" : "Please enter a valid email.";
const EmailInput = (fieldRenderProps) => {
    const { validationMessage, visited, ...others } = fieldRenderProps;
    return (
    <div>
    <Input {...others} />
    {visited && validationMessage && <Error>{validationMessage}</Error>}
    </div>
    );
};
const App = () => {
    const handleSubmit = (dataItem) => alert(JSON.stringify(dataItem, null, 2));
    return (
    <Form
    onSubmit={handleSubmit}
    render={(formRenderProps) => (
    <FormElement
        style={{
        maxWidth: 750,
        margin: "3em auto",
        }}
    >
        <fieldset className={"k-form-fieldset"}>
        <legend className={"k-form-legend"}>Contact Form</legend>
        <div style={{ margin: "1em 0" }}>
        <Field name={"firstName"} component={Input} label={"Email"} />
        </div>
        <div style={{ margin: "1em 0" }}>
        <Field
        name={"lastName"}
        component={EmailInput}
        validator={emailValidator}
        label={"First Name"}
        />
        </div>
        <div style={{ margin: "2em 0" }}>
        <Field
        name={"email"}
        type={"email"}
        component={TextArea}
        label={"Email"}
        />
        </div>
        </fieldset>
        <div className="k-form-buttons">
        <button
        type={"submit"}
        className="k-button k-button-md k-rounded-md k-button-solid k-button-solid-base"
        disabled={!formRenderProps.allowSubmit}
        >
        Submit
        </button>
        </div>
    </FormElement>
    )}
    />
    );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

The image below shows a finished copy of the demo contact form project.

The completed React contact form.

It’s good to mention that the KendoReact team has developed extensive Form Design Guidelines based on their long experience building UI components. The guidelines are freely available on their website, and you can reference it to learn more about how to build good-looking forms and UX best practices even if you’re not using the KendoReact Form itself.

Conclusion

In this post, we built a React contact form demo project with the React Form component provided by the KendoReact library. The KendoReact Form can be used to create any form—which can be effortlessly integrated into any existing project.

Top comments (2)

Collapse
 
samueldapte profile image
Kazuya Nomura

Hi, Chinedu Imoh.
Thank you for your posting.
I have one question.
How can I contact you in direct message?
Please let me know your Telegram ID, or Discord, or email, or Skype link.
I have lots of things to ask you and discuss together.
Thank you && Best Regards.
Kazuya Nomura

Collapse
 
chineduimoh profile image
Chinedu Imoh

Hello Kazuya,
Here's my email: chineduimoh@gmail.com.