How to create a contact form in React.js for beginners"
Tags: react, javascript, html, a11y
Published: 2021-09-15 10:40:13

A contact form is one of the most essential parts of any website… blah blah blah.🗣
 
You already know this.
 
You are here because you know how important forms are. And you want to create one I guess.

Welcome, today we will learn how to create a form using Reactjs.

Here's what we will be building: [React-form](https://tutorial-react-form.netlify.app/).

It's simple, has no fancy UI, and is somehow useless.

GitHub repo: [github.com/aminequ/react-form](https://github.com/aminequ/react-form)

**Prerequisites:**

1. Basic knowledge of React stateless components.
2. Basic knowledge of CSS/Sass.

That's it. Let's begin.

#Setting up the environment.

Create a react project using either npm or yarn. Both work well.

`npx create-react-app form`

Nope, I didn't trick you! npx is the same as npm. 

We will be using Sass as a preprocessor. But I promise I won't bother you with any styling.

Install `node-sass` like this:

`npm install node-sass`

Open the project with your beloved code editor then delete the default unnecessary files. If you have never done that, here's how, otherwise you can skip this part.

Delete these:

`App.test.js`
`reportWebVitals.js`
`setupTests.js`

Remove the default code and styles from `App.js/App.css/index.js/index.css`

`App.js` should only contain the App function that returns an empty `div`.

Now create a new folder inside the `src` folder and give it the name of "components", then create a new component and name it `Form.js`. Also, create a stylesheet and name it "formStyle.scss".

Start the local server: 

`npm start`

#Adding style.


I said it before, it's nothing fancy but if you want me to explain all the styling, then please, feel free to leave a comment. For now, just copy the styling from the GitHub repo and place it where it should be placed ( formStyle.scss ) 😎

#Let's code the form.


Following written coding tutorials can be tricky sometimes but I will help you, so code this inside the `Form.js` component:

```
import React from 'react'
import './formStyle.scss'

function Form() {
   return(
      <div className="container">
   </div>
 )
}
export default Form

```

We imported react, the styling, and created a stateless function with the name of "Form" . The function returns a <div> with a class name of "container".

Inside the container, go on and:

Add an `<h1>` with "Contact us".

Create a form element and give it the class name of "form".

Create a `div ` with a class name of "name". This will act as a container for first and last name fields.

Add a `<label>` tag with an attribute of `for="firsrName"`.

Check out this quote about the <label> tag:

>…This is the most important element if you want to build accessible forms - when implemented properly, screenreaders will speak a form element's label along with any related instructions, as well as it being useful for sighted users.

However, always remember to include the "for" attribute.

Now add an `<input>` element with the following attributes:

`type="text"`
`name="firstName"`
`className="firstName"`
`tabIndex="1"`


To make our form accessible, we put the "tabIndex" attribute to help the users tab through the form with the order we want and not the default order elements are coded. 

In this case, we gave the first-name number one which means it's going to be the first input the user will tab through.

Now, repeat and create another <label> and <input> elements for last name.Put same attributes, but change the word the "first" with "last" and give `thetabeIndex` attribute the value of "2".

The output code:

```
<div className="container">
  <h1>Contact us</h1>
  
 <form className="form">
     
    <div className="name">
       
       <label for="firstName">First name</label>
       <input
            type="text"
            name="firstName"
            className="firstName"
            tabIndex="1"
       />
       <label for="lastName">Last name</label>
       <input
            type="text"
            name="lastName"
            className="lastName"
            tabIndex="2"
       />
    </div>
 </form>
</div>
```
Let's create the email input field.

```
<label for="email">Email</label>
<input
     type="email"
     name="email"
     id="email"
     className="email"
     placeholder="example@corp.com"
     tabIndex="3"
/>
```

Almost nothing new, we added a `<label>` with the `for` attribute with the value of "email" and a string of "Email". Next, add an `<input>` with almost the same attributes.

We gave the email input the `tabeIndex` of "3" so it's the third filed the user will tab through.

Let's go for the message input which will not be an <input> element but a <textarea>. The difference? It's so simple.

We use the <input> when we want to have a one-line text field just like in name and email. <textarea> is for multiple line text. Here, a message could be a one-sentence, a paragraph, or a whole cover letter.

I usually post such semantic tips and other front-end development tricks on my [Twitter](https://medium.com/r/?url=https%3A%2F%2Ftwitter.com%2FAmiineQu) and [Instagram](https://medium.com/r/?url=https%3A%2F%2Fwww.instagram.com%2Famin3.js%2F). I invite you to follow me and fill your feed with useful content.

Now add a `<label>` with a for attribute and text of "message". Add a `<textarea>` tag with the attributes of: `name/className/placeholder`. 

Output code:

```
<label for="message">Message</label>

<textarea
  placeholder="Start typing..."
  className="message"
  name="message"
/>
```
let's add a submit button which is going to be the cherry on the cack. 

Create a <button> element with the type of submit and a className of "send":

```
<button type="submit" className="send">Send</button>
```
Make sure you've put everything in place and check if the form looks as in the live version

If there's an error, go back and check the output codes or refer to the code in the repo. 

All good?

#Make it functional with useRef()

Our form will only be functional when we are able to take the data submitted by the user and store it into an object, then do something with it later.

Let's first understand what exactly is the useRef() hook. In short, hooks let you use React features without writing a class and useRef() is one of these features. 

Okay! And what does this feature of useRef() do?

>Refs provide a way to access DOM nodes or React elements created in the render method.

useRef() can be a replacement for useState(). It behaves exactly as useState() except that the latest triggers a re-render while useRef() doesn't. 

useRef returns an object with a property called current and it refers to the current node or element targeted by the hook. You will understand this in a few seconds. 

In order to work with `useRef()` hook, first we need to import it just like how we import useState and other hooks. 

`import React, { useRef} from 'react'`

Here's the syntax:

`const whereWeStoreInputValue= useRef(initialValue)`

Let's implement it into our form. 

Create the following variables inside the Form component but not inside JSX of course. 

Each input should have its own variable.

```
const firstNameRef = useRef(null)
const lastNameRef =  useRef(null)
const emailRef = useRef(null)
const messageRef =  useRef(null)
```

Notice that we used null as an initial value because we want no value at the beginning. You can use an empty string instead.

Now we need to go back to the form inputs and add the `ref={}` attribute.

in each input in the form, add the ref attribute with corresponded variable. 

For example, The field responsible for Firstname can have the following attribute `ref={firstNameRef}`

That will connect the useRef variable with the right element. Get it?

Now let's create a function that will handle the submission of the form. We want to a function that will contain the retrieved data and store it in an object. 

Code this inside the `Form` component and right below the four variables we created previously:

```
const handleSubmit = (event) => {
      event.preventDefault()
      
      const data = {
            firstName: firstNameRef.current.value,
            lastName: lastNameRef.current.value,
            email: emailRef.current.value,
            message: messageRef.current.value
            }
      alert("tadaaa!: \n" + JSON.stringify(data) + "Your data 😎")
}
```

The function has the event as an argument. We use "event" with the well-known method "preventDefault" to stop the browser from performing the default behavior of the target element, in our case, it's refreshing the page. 

Next, we created an object with four properties, each property contains the reference to the current value of the targeted element. 

For example, in the code above, we put `ref={firstNameRef}` inside the first name input, then we referred to it back in the object data:

`firstName: firstNameRef.current.value`

For the scope of this article, we only alert the data back to the user. 🤷‍♂️ 

Again, check if everything works, if not, go back to where you think missed up.
 
That's for this part. In the next one, we will see how can validate the user inputs before we pass them to the `data` object.

If you feel like you've learned something new, share this article, someone somewhere is looking for it. They will appreciate you and consider you as their saver. 

See you.