Skip to main content

Building a Registration Form with React, react-hook-form,spring-boot, and axios

signup form using react-hook-form is using Axios as HTTP client and in the backend it is using spring boot API : 

import React,{ useState } from 'react';
// import { useState } from "react";
import { useForm } from "react-hook-form";
import axios from "axios";

const RegistrationForm = () => {
const { register, handleSubmit, formState: { errors } ,getValues, reset } = useForm();
const [submitting, setSubmitting] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [successMessage, setSuccessMessage] = useState("");

const onSubmit = (data) => {
setSubmitting(true);
axios.post("http://localhost:8080/register", data)
.then((response) => {
// console.log(response.data);
setSubmitting(false);
setSuccessMessage("Signup successfully!");
setErrorMessage("")
reset(); // clear the form inputs after successful submission,
})
.catch((error) => {
// console.log(error);
setErrorMessage("An error occurred while signup.");
setSuccessMessage("")
setSubmitting(false);
});
};

return (
<div className="container">
<div className="row justify-content-center">
<div className="col-lg-6 col-md-8">
<h2 className="mb-3">Sign up</h2>

{errorMessage && <div className="alert alert-danger m-3">{errorMessage}</div>}
{successMessage && <div className="alert alert-success m-3">{successMessage}</div>}

<form onSubmit={handleSubmit(onSubmit)} noValidate autoComplete="off" >


<div className="form-group">
<label htmlFor="email">Email address</label>
<input
type="email"
className={`form-control ${errors.email ? "is-invalid" : ""}`}
id="email"
{...register("email", {
required: "Email is required",
pattern: {
value: /^\S+@\S+$/i,
message: "Please enter a valid email address",
},
})}
/>
{errors.email && <div className="invalid-feedback">{errors.email.message}</div>}
</div>

<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className={`form-control ${errors.password ? "is-invalid" : ""}`}
id="password"
{...register("password", {
required: "Password is required",
minLength: {
value: 8,
message: "Password must be at least 8 characters long",
},
})}
/>
{errors.password && <div className="invalid-feedback">{errors.password.message}</div>}
</div>

<div className="form-group">
<label htmlFor="confirmPassword">Confirm Password</label>
<input
type="password"
className={`form-control ${errors.confirmPassword ? "is-invalid" : ""}`}
id="confirmPassword"
{...register("confirmPassword", {
validate: (value) =>
value === getValues("password") || "Passwords do not match",
})}
/>
{errors.confirmPassword && <div className="invalid-feedback">{errors.confirmPassword.message}</div>}
</div>

<button type="submit" className="btn btn-primary mt-5" disabled={submitting}>
{submitting ? "Signing up..." : "Sign up"}
</button>
</form>
</div>
</div>
</div>
);
};

export default RegistrationForm;

the server-side spring boot controller looks like this:


package com.gurucodetalks.Backend.controller;

import com.gurucodetalks.Backend.dto.UserRegistrationRequest;
import com.gurucodetalks.Backend.entity.User;
import com.gurucodetalks.Backend.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@CrossOrigin(origins = "http://localhost:3000")
@RestController
@RequestMapping("/register")
public class UserController {
private final UserRepository userRepository;

@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}

@PostMapping
public ResponseEntity<?> register(@RequestBody UserRegistrationRequest request) {
if (userRepository.existsByEmail(request.getEmail())) {
return ResponseEntity.badRequest().body("Email already exists");
}

User user = new User(request.getEmail(), request.getPassword());
userRepository.save(user);

return ResponseEntity.ok("User registered successfully");
}
}

full code available here: https://github.com/sudeepcv/registration-form-react-hook-form

Comments

Popular posts from this blog

a simple example for jdbc PreparedStatement

a simple example for PreparedStatement package basics.in.java.blogspot.in; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Main { private static final String USERNAME="root"; private static final String PASSWORD=""; private static final String CONN_STRING="jdbc:mysql://localhost/basicsinjavablogspot"; public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection conn=null; Statement stmt=null; ResultSet rs=null; try { conn= DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); System.out.println("database connection successful"); //stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); String sql="select * fr...

Server-Side Pagination with React-Table and Spring Boot JPA with H2 Database

Pagination is a common technique used to split large amounts of data into smaller, more manageable chunks. With server-side pagination, data is retrieved from the server in smaller batches, reducing the amount of data transferred over the network and improving application performance. React-Table provides a wide range of built-in features such as sorting, filtering, pagination, row selection, and column resizing. These features can be easily configured and customized to fit specific requirements. For example, you can customize the sorting behavior to handle multiple sorting criteria, or you can add custom filters to the table to handle complex data filtering scenarios. Additionally, React-Table provides a flexible API that allows developers to extend its functionality with custom hooks, plugins, and components. This means that you can easily add custom functionality to the table, such as exporting data to CSV or integrating with external data sources. In terms of styl...