Registration Page in React Using Formik, Web API and SQL

Introduction 

 
In this article, I'm going to create an application to perform the registration page of a user and display the user details in React Js with Axios using Web API. We look at how to use Formik with the help of an example. The backend is a SQL Server database.
 
Mainly, we will see how to check the form validation easily and quickly before submitting the data on our registration page. We will transfer the data or consume the data in UI from an application using a Web API. A Web API is used to provide data connectivity between the database and the front end application and building Restful services. On the UI side, I will use Formik and react-bootstrap to create a rich, interactive, device-independent user experience. It's often used to build a beautiful UI. In this example, I will create a registration page and bind the user details. Let's see step by step.
 
First, take a look at our output...
 
Registration Page In React Using Formik, Web API And SQL
 
I'm using Visual Studio Code as a tool to build my application. If you don't have Visual studio code in your system, then first you have to download and install it. Here is the Visual Studio Code download link: Download Visual Studio Code Editor
 
Prerequisites
  • Visual studio
  • SQL Server
  • Node.js version > 10
  • React
  • React Axios
  • Formik
  • Visual studio code
  • Bootstrap
  • React-toastify
  • React-bootstrap
Step1. Create a database and table
 
Create a database. Open SQL Server and create a new database and table. As you can see from the following query, you must use the below SQL Script to create the required ReactDB Database. The table is UserDetails
  1. CREATE TABLE [dbo].[UserDetails](  
  2.   [UserId] [int] IDENTITY(1, 1) NOT NULL,   
  3.   [FirstName] [varchar](50) NULL,   
  4.   [LastName] [varchar](50) NULL,   
  5.   [EmailId] [varchar](100) NULL,   
  6.   [Password] [varchar](50) NULL,   
  7.   [MobileNo] [varchar](50) NULL,   
  8.   [Address] [varchar](500) NULL,   
  9.   [PinCode] [char](10) NULL,   
  10.   [CompanyName] [varchar](100) NULL,   
  11.   CONSTRAINT [PK_UserDetails] PRIMARY KEY CLUSTERED ([UserId] ASCWITH (  
  12.     PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,   
  13.     IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,   
  14.     ALLOW_PAGE_LOCKS = ON  
  15.   ) ON [PRIMARY]  
  16. )  
Step 2. Create a Web API Project

Now, we will create a Web API with registration page functionality, then bind the user details from a database. Go to Visual Studio >> File >> New >> Project, and select Web Application. After that, click OK and you will see the templates. Select the Web API template.
 
Registration Page In React Using Formik, Web API And SQL
 
Once you click on the OK button, a new dialog will pop up for selecting project templates, as shown in the below image. 
 
Registration Page In React Using Formik, Web API And SQL
 
Click OK.
 
Step3: Adding ADO.NET Entity Data Model
 
Right-Click on Models Folder, then select Add >> New Item from the context menu which will open the Add New Item window. From the “Add New Item” window, from the left pane expand, Installed >> Visual C# >> Data option. From the middle pane, select the ADO.NET Entity Data Model template. Provide a meaningful name to your data model such as MyDataModel, then finally, click on the Add button as shown in the below image.
 
Registration Page In React Using Formik, Web API And SQL
 
From the next screen, we are going to use the Entity Framework Database First approach. Select EF Designer from Database from Entity Data Model Wizard and click on the Next button, as shown in the image below.
 
Registration Page In React Using Formik, Web API And SQL
 
In the next step, click on the new connection from Choose your data connection wizard, as shown below.
 
Registration Page In React Using Formik, Web API And SQL
 
Provide the necessary details to communicate with the database, such as Server name. Select the Authentication Type, select the Database, then click on the Ok button, as shown below. 
 
Registration Page In React Using Formik, Web API And SQL
 
Click the Next button
 
Registration Page In React Using Formik, Web API And SQL
 
Above, we need to select the database object for our application. We then need to select that UserDetailsTable and finally, click on the Finish button.
 
See our table entity:
Registration Page In React Using Formik, Web API And SQL
The framework will create the EDMX file within the Models folder. 
 
Registration Page In React Using Formik, Web API And SQL
 
Step 4. Add API controller logic
 
Go to the Controller folder in our API Application and right-click >> Add >> Controller >> Select Web API 2 Controller-Empty
 
Registration Page In React Using Formik, Web API And SQL
 
Click Add button
 
Now we will write the logic to bind the data and register the user data. We will go to the controller class and set the attribute routing to make it more user-friendly by writing the below code. 
  1. using ReactDemoAPI.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web.Http;  
  6. namespace ReactDemoAPI.Controllers {  
  7.     [RoutePrefix("Api/User")]  
  8.     public class UserAPIController: ApiController {  
  9.         [HttpGet]  
  10.         [Route("GetUserDetails")]  
  11.         public IEnumerable < UserDetail > GetUser() {  
  12.                 try {  
  13.                     ReactDBEntities objEntity = new ReactDBEntities();  
  14.                     return objEntity.UserDetails.ToList();  
  15.                 } catch (Exception) {  
  16.                     throw;  
  17.                 }  
  18.             }  
  19.             [HttpPost]  
  20.             [Route("InsertUserData")]  
  21.         public string AddUserData(UserDetail data) {  
  22.             try {  
  23.                 ReactDBEntities objEntity = new ReactDBEntities();  
  24.                 objEntity.UserDetails.Add(data);  
  25.                 int result = objEntity.SaveChanges();  
  26.                 if (result > 0) {  
  27.                     return "Data has been inserted";  
  28.                 } else {  
  29.                     return "Data insetion has been faild";  
  30.                 }  
  31.             } catch (Exception) {  
  32.                 throw;  
  33.             }  
  34.         }  
  35.     }  
  36. }  
Now, our API has been completed. As you may see from the above code, it has the functionality to bind and register the user data.
 
Step 5.Create and Install React js
 
Now we will create a react project thought below command. But before that just check Node and NPM installed or not. Also, we are using Visual Studio code to write Angular code for a UI application. First, make sure it is installed. If not installed, then go to this link to download it.
 
Let's create a react project to open a new terminal and run the following command to install and create a react project.
 
npx create-react-app formikexample-app
 
Registration Page In React Using Formik, Web API And SQL
 Registration Page In React Using Formik, Web API And SQL
 
Your React project has been created.
 
Step 6. Set Visual studio code for react
 
Open Visual Studio Code and go inside the folder. Open the project inside the visual studio code.
 
Registration Page In React Using Formik, Web API And SQL
 
Select the correct folder.
 
Registration Page In React Using Formik, Web API And SQL
 
Click on the Select Folder button.
 
 
Step 7. Install bootstrap
 
Now, we will install bootstrap to building a beautiful UI of our react application.
 
npm install bootstrap --save
 
Next, we will install react-bootstrap bootstrap for design table, button, etc.
 
npm install react-bootstrap bootstrap
 
Registration Page In React Using Formik, Web API And SQL
 
Step 8. Install Axios library
 
Axios is a modern and promise based java scrip HTTP client library which is works asynchronously and allows us to make HTTP calls and consume to REST API.
 
Let's install Axios in our React project using the following command.
 
npm install --save axios
 
Registration Page In React Using Formik, Web API And SQL
 
Step 9. Introduction Formik
 
Formik is a small group of react components and hooks for building forms to React and React Native. It helps with the three most annoying parts:
  1. Getting values in and out of form state.
  2. Validation and error messages
  3. Handling form submission
Generally, we pass our form's initial values and a submission function to the useFormik() hook. The hook then returns all values in the group of form state and helpers in a variable we are calling formik.
  • handleSubmit: A submission handler
  • handleChange: A change handler to pass to each <input>, <select>, or <textarea>
  • values: Our form's current values 
 For more details, you can follow the Formik Doc.
 
Step 10. Install Formik
 
Go to Terminal and set the Project path. Type the below command:
 
npm install formik
 
Registration Page In React Using Formik, Web API And SQL
Step 11. Install Yup
 
Yup is a JavaScript object schema validator and an immutable object responsible for validating an object. It makes our lives far easier for validating the data our apps consume and manipulate.
 
Install Yup with the below command:
 
 npm install yup--save
Registration Page In React Using Formik, Web API And SQL
Step 12. Install react-toastify
 
React-Toastify allow us to add notifications to our app. We can get the notification with an interactive popup UI.
 
Install the react-toastify with the below command:
 
npm install yup--save
 
Registration Page In React Using Formik, Web API And SQL
 
Step 13. Check to react dependency
 
Go to the package.json file and check the React dependency.
 
Registration Page In React Using Formik, Web API And SQL
 
Step 14. Add React Component
 
Go inside the src folder and create a new folder. Here, I created a form folder with 2 files.
 
UserDetails.js
UserValidationSchema.js
 
Registration Page In React Using Formik, Web API And SQL
 
Step 15. Write code in js file to perform our operation
 
Now we will write our logic to perform a validation of the registration page.
 
Open UserValidationSchema.js file and write the validation of properties of the registration page.
 
First, import dependency libraries. 
  1. import * as Yup from "yup";  
  2.   
  3. export const UserValidationSchema = Yup.object().shape({  
  4.   
  5. firstName: Yup.string()  
  6. .required('First Name is required'),  
  7. lastName: Yup.string()  
  8. .required('Last Name is required'),  
  9. emailId: Yup.string()  
  10. .email('Email is invalid')  
  11. .required('Email is required'),  
  12. password: Yup.string()  
  13. .min(6, 'Password must be at least 6 characters')  
  14. .required('Password is required'),  
  15. confirmPassword: Yup.string()  
  16. .oneOf([Yup.ref('password'), null], 'Passwords must match')  
  17. .required('Confirm Password is required'),  
  18. mobileNo: Yup.string()  
  19. .required('Mobile Numer is required'),  
  20. address: Yup.string()  
  21. .required('Address is required'),  
  22. pinCode: Yup.string()  
  23. .min(6, 'Password must be at 6 digits')  
  24. .max(6,'Password must be at 6 digits')  
  25. .required('Pin Code is required'),  
  26. companyName: Yup.string()  
  27. .required('Company Name is required')  
  28. });  
Now go inside the Forms folder and open UserDetails.js file and import the necessary library, then write the below code in the file.
  • Add necessary library
  • Create a custom function for mobile validation
  • Declare the properties in state
  • Write a method for bind user details in component did mount
  • Declare the properties in intialValues
  • Design the registration page with formik.
  • Set the error message
  • Write the logic for submitting the data 
  1. import React from 'react';  
  2. import { Formik, Field, Form, ErrorMessage } from 'formik';  
  3. import {  
  4. Row,  
  5. Col,  
  6. Container,  
  7. Table  
  8. } from 'react-bootstrap';  
  9. import Axios from 'axios';  
  10. import { toast } from 'react-toastify';  
  11. import 'react-toastify/dist/ReactToastify.css';  
  12. import 'bootstrap/dist/css/bootstrap.css';  
  13. import { UserValidationSchema } from "./UserValidationSchema";  
  14.   
  15. toast.configure()  
  16. toast.configure({  
  17.    autoClose: 8000,  
  18.    draggable: false,  
  19. });  
  20. const apiUrl = "http://localhost:63377/Api/User";  
  21.   
  22. function validateMobile(value) {  
  23.    let error = '';  
  24.    const mob = /^[1-9]{1}[0-9]{9}$/;  
  25.    if (value === '') {  
  26.       error = 'Required';  
  27.    } else if (!mob.test(value)) {  
  28.       error = 'Invalid mobile number';  
  29.       }  
  30.    return error;  
  31. }  
  32.   
  33. class UserDetails extends React.Component {  
  34. state = {  
  35.    userData: {},  
  36.    userList: [],  
  37. }  
  38.   
  39. componentDidMount() {  
  40.    this.bindUserData();  
  41. }  
  42. bindUserData() {  
  43.    Axios.get(`${apiUrl}/GetUserDetails`).then(  
  44.    (result) => {  
  45.       this.setState({  
  46.       userList: result.data,  
  47.       });  
  48.    },  
  49. (error) => {  
  50.    this.setState({  
  51.    error  
  52.    });  
  53. })  
  54. }  
  55.   
  56. render() {  
  57.    const txtAlign = {  
  58.    'textAlign''left'  
  59. }  
  60.   
  61. const colStyle = {  
  62.    backgroundColor: '#002b48',  
  63.    color: "#ffffff",  
  64.    width: '60px'  
  65. }  
  66. return (  
  67.   
  68.    <Formik  
  69.       validationSchema={UserValidationSchema}  
  70.       initialValues={{  
  71.       firstName: '',  
  72.       lastName: '',  
  73.       emailId: '',  
  74.       password: '',  
  75.       confirmPassword: '',  
  76.       mobileNo: '',  
  77.       address: '',  
  78.       pinCode: '',  
  79.       companyName: '',  
  80.    }}  
  81.   
  82. onSubmit={async (input, { resetForm }) => {  
  83.    await Axios.post(`${apiUrl}/InsertUserData`, input).then(res => {  
  84.       toast.success(res.data)  
  85.       this.bindUserData();  
  86.       resetForm({})  
  87.    })  
  88. .catch(err => {  
  89.    toast.error('Something went wrong.');  
  90. });  
  91. }  
  92. }  
  93. render={({ errors, touched }) => (  
  94.   
  95.     <Container>  
  96.         <Form>  
  97.             <Row>  
  98.                 <Col>  
  99.                     <h2>Registration Page uisng Formik</h2>  
  100.                     <hr />  
  101.                 </Col>  
  102.             </Row>  
  103.             <Row>  
  104.                 <Col className="form-group" md={4} sm={4} xs={4} style={txtAlign}>  
  105.                     <label htmlFor="firstName">First Name</label>  
  106.                     <Field name="firstName" type="text" className={'form-control' + (errors.firstName && touched.firstName ? ' is-invalid' : '')} />  
  107.                     <ErrorMessage name="firstName" component="div" className="invalid-feedback" />  
  108.                 </Col>  
  109.                 <Col className="form-group" md={4} sm={4} xs={4} style={txtAlign}>  
  110.                     <label htmlFor="lastName">Last Name</label>  
  111.                     <Field name="lastName" type="text" className={'form-control' + (errors.lastName && touched.lastName ? ' is-invalid' : '')} />  
  112.                     <ErrorMessage name="lastName" component="div" className="invalid-feedback" />  
  113.                 </Col>  
  114.                 <Col md={4} className="form-group" sm={4} xs={4} style={txtAlign}>  
  115.                     <label htmlFor="emailId">Email Name</label>  
  116.                     <Field name="emailId" type="text" className={'form-control' + (errors.emailId && touched.emailId ? ' is-invalid' : '')} />  
  117.                     <ErrorMessage name="emailId" component="div" className="invalid-feedback" />  
  118.                 </Col>  
  119.             </Row>  
  120.             <Row>  
  121.                 <Col className="form-group" md={4} sm={4} xs={4} style={txtAlign}>  
  122.                     <label htmlFor="password">Password</label>  
  123.                     <Field name="password" type="text" className={'form-control' + (errors.password && touched.password ? ' is-invalid' : '')} />  
  124.                     <ErrorMessage name="password" component="div" className="invalid-feedback" />  
  125.                 </Col>  
  126.                 <Col className="form-group" md={4} sm={4} xs={4} style={txtAlign}>  
  127.                     <label htmlFor="confirmPassword">Confirm Password</label>  
  128.                     <Field name="confirmPassword" type="text" className={'form-control' + (errors.confirmPassword && touched.confirmPassword ? ' is-invalid' : '')} />  
  129.                     <ErrorMessage name="confirmPassword" component="div" className="invalid-feedback" />  
  130.                 </Col>  
  131.                 <Col className="form-group" md={4} sm={4} xs={4} style={txtAlign}>  
  132.                     <label htmlFor="address">Address</label>  
  133.                     <Field name="address" type="text" className={'form-control' + (errors.address && touched.address ? ' is-invalid' : '')} />  
  134.                     <ErrorMessage name="address" component="div" className="invalid-feedback" />  
  135.                 </Col>  
  136.             </Row>  
  137.             <Row>  
  138.                 <Col md={8} sm={8} xs={8}>  
  139.                     <Row>  
  140.                         <Col className="form-group" md={6} sm={6} xs={6} style={txtAlign}>  
  141.                             <label htmlFor="pinCode">Pin Code</label>  
  142.                             <Field name="pinCode" type="text" className={'form-control' + (errors.pinCode && touched.pinCode ? ' is-invalid' : '')} />  
  143.                             <ErrorMessage name="pinCode" component="div" className="invalid-feedback" />  
  144.                         </Col>  
  145.                         <Col className="form-group" md={6} sm={6} xs={6} style={txtAlign}>  
  146.                             <label htmlFor="companyName">Company Name</label>  
  147.                             <Field name="companyName" type="text" className={'form-control' + (errors.companyName && touched.companyName ? ' is-invalid' : '')} />  
  148.                             <ErrorMessage name="companyName" component="div" className="invalid-feedback" />  
  149.                         </Col>  
  150.                     </Row>  
  151.                 </Col>  
  152.                 <Col className="form-group" md={4} sm={4} xs={4} style={txtAlign}>  
  153.                     <label htmlFor="mobileNo">Mobile No</label>  
  154.                     <Field validate={validateMobile} name="mobileNo" type="text" size={'sm'} className={'form-control' + (errors.mobileNo && touched.mobileNo ? ' is-invalid' : '')} />  
  155.                     <ErrorMessage name="mobileNo" component="div" className="invalid-feedback" />  
  156.                 </Col>  
  157.             </Row>  
  158.             <Row>  
  159.                 <Col>  
  160.                     <button type="submit" className="btn btn-primary mr-2">Register</button>  
  161.                     <button type="reset" className="btn btn-secondary">Reset</button>  
  162.                 </Col>  
  163.             </Row>  
  164.         </Form>  
  165.         <hr/>  
  166.         <Row>  
  167.             <Col>  
  168.                 <Table striped bordered hover size="sm">  
  169.                     <thead style={colStyle}>  
  170.                         <tr>  
  171.                             <th>Sr.No</th>  
  172.                             <th>First Name</th>  
  173.                             <th>Last Name</th>  
  174.                             <th>Email Id</th>  
  175.                             <th>Mobile No</th>  
  176.                             <th>Address</th>  
  177.                             <th>Pine Code</th>  
  178.                             <th>Company Name</th>  
  179.                         </tr>  
  180.                     </thead>  
  181.                     <tbody>  
  182. {this.state.userList.map((user, i) => (  
  183.   
  184.                         <tr key={user.UserId}>  
  185.                             <td>{i + 1}</td>  
  186.                             <td>{user.FirstName}</td>  
  187.                             <td>{user.LastName}</td>  
  188.                             <td>{user.EmailId}</td>  
  189.                             <td>{user.MobileNo}</td>  
  190.                             <td>{user.Address}</td>  
  191.                             <td>{user.PinCode}</td>  
  192.                             <td>{user.CompanyName}</td>  
  193.                         </tr>  
  194. ))}  
  195.   
  196.   
  197.                     </tbody>  
  198.                 </Table>  
  199.             </Col>  
  200.         </Row>  
  201.     </Container>  
  202. )}  
  203. />  
  204. )  
  205. }  
  206. }  
  207.   
  208. export default UserDetails;  
Now open index.js file and First import necessary library and add root component.
  1. import React from 'react';  
  2. import './App.css';  
  3. import UserDetails from './Forms/UserDetails';  
  4.   
  5. function App() {  
  6.    return (  
  7.       <div className="App">  
  8.          <UserDetails/>  
  9.       </div>  
  10.       );  
  11.    }  
  12.   
  13. export default App;  
Finally, our coding part also has been completed.
 
Step 16. Set CORS (Cross-Origin Resource Sharing)
 
Go to the Web API project.
 
Download a NuGet package for CORS. Go to NuGet Package Manager and download the following file.
 
After that, go to the App_Start folder in Web API project and open WebApiConfig.cs class. Here, modify the Register method with the below code.
 
Registration Page In React Using Formik, Web API And SQL
 
Add namespace
  1. using System.Web.Http.Cors;  
After that, add the below code inside the Register method.
  1. var cors = new EnableCorsAttribute("*""*""*");  
  2. config.EnableCors(cors);  
Step 17. Run
 
We have completed all the needed code functionality. Before running the application, first, make sure to save your work.
 
Now, let's run the app and see how it works.
 
Open TERMINAL and write the following command to run the program.
 
npm start
 
The output looks like the following image. There's a stunning UI that's been created.
 
Registration Page In React Using Formik, Web API And SQL
 

Conclusion

 
We have completed an operation to the registration page with validation using Formik in React and Axios using Web API and SQL server. We started by installing and creating the create-react-app, then used it to create our React project. Next, we installed bootstrap and react-bootstrap and react-bootstrap-table-next in the React application. After that, we installed the Axios client and the Formik library.
 
I hope this article helps you with your needs, such as quick and easy validation functionality. I would like your feedback, so please post your feedback, questions, or comments about this article!