In this tutorial i will show how to create a form with validation using Formik and yup with bootstrap and PHP Mysql to save data form.
Formik : https://formik.org/
Yup : https://www.npmjs.com/package/yup
Bootstrap : https://react-bootstrap.github.io/getting-started/introduction/
Axios : https://github.com/axios/axios
Install Formik
npm install formik yup
C:\reactdev\myreactdev>npm install formik yup
https://github.com/axios/axios
Installing the Axios Client
$ npm install axios
C:\reactdev\myreactdev>npm install axios
Install bootstrap
npm install react-bootstrap bootstrap@5.1.3
C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3
https://react-bootstrap.github.io/getting-started/introduction/
CREATE TABLE `tbl_signup` (
`id` int(11) NOT NULL,
`firstName` varchar(150) NOT NULL,
`lastName` varchar(150) NOT NULL,
`email` varchar(150) NOT NULL,
`password` varchar(150) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tbl_signup`
ADD PRIMARY KEY (`id`);
ALTER TABLE `tbl_signup`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
//src/index.js import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import 'bootstrap/dist/css/bootstrap.min.css' ReactDOM.render( <App />, document.getElementById('root') )public/index.html
//public/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>ReactJS </title> </head> <body> <div id="root"></div> </body> </html>src/App.js
//src/App.js import regimg from './assets/reg.jpg'; import { Signup } from './components/Signup'; import './App.css'; function App() { return ( <div className="container mt-3"> <div className="row"> <div className="col-md-6 my-auto"> <img className="img-fluid w-100" src={regimg} alt=""/> </div> <div className="col-md-6"> <Signup /> </div> </div> </div> ); } export default App;src/App.css
//src/App.css @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap'); body { font-family: 'Roboto', sans-serif; } label { font-size: 14px; padding-bottom: 10px; } input.form-control, input.form-control:focus { background: #F0F0FF; } .error { position: absolute; color: red; font-size: 11px; }src/components/Signup.js
//src/components/Signup.js import React from 'react'; import { Formik, Form } from 'formik'; import { TextField } from './TextField'; import * as Yup from 'yup'; import axios from 'axios'; export const Signup = () => { const validate = Yup.object({ firstName: Yup.string() .max(15, 'Must be 15 characters or less') .required('Required'), lastName: Yup.string() .max(20, 'Must be 20 characters or less') .required('Required'), email: Yup.string() .email('Email is invalid') .required('Email is required'), password: Yup.string() .min(6, 'Password must be at least 6 charaters') .required('Password is required'), confirmPassword: Yup.string() .oneOf([Yup.ref('password'), null], 'Password must match') .required('Confirm password is required'), }) return ( <Formik initialValues={{ firstName: '', lastName: '', email: '', password: '', confirmPassword: '' }} validationSchema={validate} onSubmit={data => { console.log(data) let formData = new FormData(); formData.append('firstName', data.firstName) formData.append('lastName', data.lastName) formData.append('email', data.email) formData.append('password', data.password) axios({ method: 'post', url: 'http://localhost/devtest/reactjs/signup.php/', data: formData, config: { headers: {'Content-Type': 'multipart/form-data' }} }) .then(function (response) { //handle success console.log(response) alert('New User Successfully Added.'); }) .catch(function (response) { //handle error console.log(response) }); }}> {formik => ( <div> <h1 className="my-4 font-weight-bold .display-4">Sign Up</h1> <Form> <TextField label="First Name" name="firstName" type="text" /> <TextField label="last Name" name="lastName" type="text" /> <TextField label="Email" name="email" type="email" /> <TextField label="password" name="password" type="password" /> <TextField label="Confirm Password" name="confirmPassword" type="password" /> <button className="btn btn-primary mt-3" type="submit" style={{marginRight: 20}}>Register</button> <button className="btn btn-warning mt-3 ml-3" type="reset">Reset</button> </Form> </div> )} </Formik> ) }src/components/TextField.js
//src/components/TextField.js import React from 'react'; import { ErrorMessage, useField } from 'formik'; export const TextField = ({ label, ...props }) => { const [field, meta] = useField(props); return ( <div className="mb-2"> <label htmlFor={field.name}>{label}</label> <input className={`form-control shadow-none ${meta.touched && meta.error && 'is-invalid'}`} {...field} {...props} autoComplete="off" /> <ErrorMessage component="div" name={field.name} className="error" /> </div> ) }http://localhost/devtest/reactjs/signup.php
//http://localhost/devtest/reactjs/signup.php <?php header("Access-Control-Allow-Origin: *"); //add this CORS header to enable any domain to send HTTP requests to these endpoints: $host = "localhost"; $user = "root"; $password = ""; $dbname = "testingdb"; $con = mysqli_connect($host, $user, $password,$dbname); $method = $_SERVER['REQUEST_METHOD']; if (!$con) { die("Connection failed: " . mysqli_connect_error()); } switch ($method) { case 'POST': $firstName = $_POST["firstName"]; $lastName = $_POST["lastName"]; $email = $_POST["email"]; $password = $_POST["password"]; $sql = "insert into tbl_signup (firstName, lastName, email, password) values ('$firstName', '$lastName', '$email', '$password')"; break; } // run SQL statement $result = mysqli_query($con,$sql); // die if SQL statement failed if (!$result) { http_response_code(404); die(mysqli_error($con)); } if ($method == 'POST') { echo json_encode($result); } else { echo mysqli_affected_rows($con); } $con->close();