React Authentication - Register
Tags: react, auth, beginners, tutorial
Published: 2021-01-18 15:01:47

Welcome to this article where we will be consuming APIs and setting up authentication on the frontend with [Reactjs](https://reactjs.org/). This series is a continuation of the [backend series](https://dev.to/ebereplenty/hosting-a-nodejs-and-mongodb-app-on-heroku-38b8) we made a while ago using nodejs and mongoDB. You can check all the backend series in parts here: [Part 1](https://dev.to/ebereplenty/authentication-with-nodejs-and-mongodb-part-1-10pn), [Part 2](https://dev.to/ebereplenty/authentication-with-nodejs-and-mongodb-part-2-1hg9), [Part 3](https://dev.to/ebereplenty/authentication-with-nodejs-and-mongodb-part-3-3mic), [Part 4](https://dev.to/ebereplenty/authentication-with-nodejs-and-mongodb-part-4-4p37).

# Starter project
Now to the business of this article. Get your starter code from [here](https://github.com/EBEREGIT/react-auth/tree/auth-starter-code). This project is the result of our tutorial on react-bootstrap. You can check it out [here](https://dev.to/ebereplenty/introduction-to-react-bootstrap-20ik).

I will take you on a ride consuming the APIs. These APIs were documented [here](https://documenter.getpostman.com/view/13495436/TVzVibja). If you will like to learn how APIs can be documented, check out this [tutorial](https://dev.to/ebereplenty/api-documentation-with-postman-52na).

Having cloned the [starter project](https://github.com/EBEREGIT/react-auth/tree/auth-starter-code), navigate into the project folder using your terminal and run ``npm install`` and ``npm start`` to start the development server. You should have the project in your browser running on ``port:3000``. See mine below:

![Starter App](https://dev-to-uploads.s3.amazonaws.com/i/aezi8kz9yrw8j9gpppip.JPG)

# Register
To make the Registeration functional, we will need to consume the Register endpoint: ``https://nodejs-mongodb-auth-app.herokuapp.com/register``.

* Navigate into the ``Register.js`` file
* Set initial states for ``email``, ``password`` and ``register``

```javascript

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [register, setRegister] = useState(false);

```

* Set a ``name`` and ``value`` attribute for the ``email`` and ``password`` input fields. This is mine:

```javascript

{/* email */}
        <Form.Group controlId="formBasicEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control
            type="email"
            name="email"
            value={email}
            placeholder="Enter email"
          />
        </Form.Group>

        {/* password */}
        <Form.Group controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            name="password"
            value={password}
            placeholder="Password"
          />
        </Form.Group>

```
*At this point, you will notice that you can no longer type into the Register Form fields. This is because we have not set the field to update from the previous state to the current state. Let's do that*

* Add ``onChange={(e) => setEmail(e.target.value)}``
and ``onChange={(e) => setPassword(e.target.value)}`` to the ``email`` and ``password`` input fields respectively. This is mine:

```javascript

       {/* email */}
        <Form.Group controlId="formBasicEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control
            type="email"
            name="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Enter email"
          />
        </Form.Group>

        {/* password */}
        <Form.Group controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            name="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Password"
          />
        </Form.Group>

```
*Now you can type into the form fields because it is now updating the state to the content you type in*

* Add ``onSubmit={(e)=>handleSubmit(e)}`` and ``onClick={(e)=>handleSubmit(e)}`` to the ``form`` and ``button`` element respectively. **The ``onSubmit`` enables form submission using the ``Enter`` key while the ``onClick`` enables form submission by clicking the button**. Now the form looks like this:

```javascript

      <Form onSubmit={(e)=>handleSubmit(e)}>
        {/* email */}
        <Form.Group controlId="formBasicEmail">
          <Form.Label>Email address</Form.Label>
          <Form.Control
            type="email"
            name="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Enter email"
          />
        </Form.Group>

        {/* password */}
        <Form.Group controlId="formBasicPassword">
          <Form.Label>Password</Form.Label>
          <Form.Control
            type="password"
            name="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Password"
          />
        </Form.Group>

        {/* submit button */}
        <Button
          variant="primary"
          type="submit"
          onClick={(e) => handleSubmit(e)}
        >
          Register
        </Button>
      </Form>

```
* To test if this is working, create the following function just before the ``return`` line

```javascript

const handleSubmit = (e) => {
    // prevent the form from refreshing the whole page
    e.preventDefault();
    // make a popup alert showing the "submitted" text
    alert("Submited");
  }

```

*If you click the button or hit the Enter Key, this should be your result:*

![Testing the handleSubmit function](https://dev-to-uploads.s3.amazonaws.com/i/zryimfq0tsf20umz70oj.JPG)

## Building out the handleSubmit function
* Now remove the ``alert`` statement from the handleSubmit function

* Let's install Axios. *We will be using axios to call the API or connect the frontend to the backend as the case maybe*. 

```javascript

npm i axios

```

* Import axios at the top of the file like so:

```javascript

import axios from "axios";

```

* In the handleSubmit function, let's build out the configuration needed for axios to successfully connect our frontend to the backend. 

```javascript

// set configurations
    const configuration = {
      method: "post",
      url: "https://nodejs-mongodb-auth-app.herokuapp.com/register",
      data: {
        email,
        password,
      },
    };

```

**The ``method`` tells how our data will be processed, ``url`` is the endpoint through which the API function will be accessed and ``data`` contains all the input or ``request body`` that the backend is expecting. Hopefully that is clear enough.**

* Having the configurations setup, let's now make the call. The API call is just a one-line statement. Here:

```javascript

axios(configuration)

```
*With that, the API call has been completed. However, we need to be sure if it actually succeeded or not. And maybe show the result to our users. So to fix that, we will use a then...catch... block*

* Now we have this:

```javascript

    // make the API call
    axios(configuration)
    .then((result) => {console.log(result);})
    .catch((error) => {console.log(error);})

```

*We are logging to the console just for testing purposes*

* Now try registering a new user and check the console for the result. Mine was successful. See below:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/p18oqn02fsqe0hx2qnlc.JPG)

*Of course we will not direct our users to the console to check for the result of their registration. So let's find a way to communicate to the user*

* Replace the code with the following code:

```javascript

    // make the API call
    axios(configuration)
      .then((result) => {
        setRegister(true);
      })
      .catch((error) => {
        error = new Error();
      });

```
*By setting register to ``true``, we can now tell when the registration process is completed. So let's tell the user*

* Add the following code in the ``Form`` element

```javascript

      {/* display success message */}
        {register ? (
          <p className="text-success">You Are Registered Successfully</p>
        ) : (
          <p className="text-danger">You Are Not Registered</p>
        )}

```
*The code is a conditional statement to display success message when the ``register`` is ``true``. Now let's give it a try*

This is mine:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/mbavmdxdhuleb9259rf1.gif)

If you are getting same result as mine, then you did it!!!

You are awesome

### Conclusion
This is the beginning of another authentication series from your truly. But this time, it is on the frontend using REACT library. We have seen how to register a user.

All codes are [here](https://github.com/EBEREGIT/react-auth/tree/register)

Next we will be looking at how to login a user and give then a token of Authorization. Stick with me