React Form Validation: Build a Basic React Form with reCAPTCHA
Creating a form in react might sometime seem difficult when you have to work with complex logics in large applications. For those cases, you might need to opt for react form libraries available in the internet. But for basic usage, when we can use simple forms without any library. In this tutorial we will see how to implement a basic form in React, style it, validate it without any library and enhance basic security by using recaptcha.
- Effortless Form Development in React
Lets assume, we have created a react app where we need to implement the form element. Lets say we have 3 fields to take input from user: name, email and a message. For example, a comment box in real life.
We will build a form component called, SimpleForm. Lets add the component in our app’s root:
import React from 'react';
import SimpleForm from './SimpleForm';
function App() {
return (
<div>
<h1>Simple Form Example</h1>
<SimpleForm />
</div>
);
}
export default App;
Now please create a new component file called SimpleForm.js, and please add these codes to the file:
function SimpleForm() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
// Handle form submission, you can send data to server or handle it locally.
console.log(formData);
// Optionally, you can reset the form after submission.
setFormData({
name: '',
email: '',
message: ''
});
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
<label htmlFor="message">Message:</label>
<textarea
id="message"
name="message"
value={formData.message}
onChange={handleChange}
required
></textarea>
<button type="submit">Submit</button>
</form>
);
}
export default SimpleForm;
And also please dont forget to import React and useState hook:
import React, { useState } from 'react';
- Lets have a bit explanation
Here, as planned we have 3 fields added as input.
With the handleChange method, we are saving data to formData state, here we are using useState hook in react. Also with [e.target.name], we are assigning field names dynamically so that we dont have to save each fields separately.
As the data are available in the state, with handleSubmit method, we can now submit the form-data to backend.
- Add Styling to the form Using CSS
While developing components, here form for example, you always need to style them as required. You can do inline style, or import css modules from a css file and apply styles via className. For beginners, sometimes it's difficult to apply styles from css file, but this process is very easy and straightforward. Here is a quick example:
import React, { useState } from 'react';
import styles from './SimpleForm.module.css'; // CSS Module file
function SimpleForm() {
const [formData, setFormData] = useState({ name: '', email: '', message: '' });
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
setFormData({ name: '', email: '', message: '' });
};
return (
<form onSubmit={handleSubmit} className={styles.form}>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
className={styles.input}
required
/>
{/* Additional fields */}
<button type="submit" className={styles.button}>Submit</button>
</form>
);
}
export default SimpleForm;
here is a basic example of SimpleForm.module.css (put the file in the same directory the component is):
/* SimpleForm.module.css */
.form {
display: flex;
flex-direction: column;
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
background-color: #f9f9f9;
}
.label {
margin-bottom: 5px;
font-weight: 500;
}
.input, .textarea {
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
width: 100%;
}
.input:focus, .textarea:focus {
border-color: #007bff;
outline: none;
}
.button {
padding: 10px 15px;
border: none;
border-radius: 5px;
background-color: #007bff;
color: white;
cursor: pointer;
font-size: 16px;
}
.button:hover {
background-color: #0056b3;
}
- Enhance User Experience with Real-Time Validation
In real world scenario, you can also add some basic validations to improve form handling better. For simple logics, you can just directly add logics to test data is in proper format before submitting it for backend. Obviously we can use libraries to do these things very effectively while handling complex forms, but before that you need to know the basic ways to implement validation rules.
Lets see a quick example:
Lets see a quick example:
const [errors, setErrors] = useState({
name: '',
email: '',
message: ''
});
const validateForm = () => {
const newErrors = {};
if (!formData.name.trim()) newErrors.name = "Name is required.";
if (!formData.email.includes("@")) newErrors.email = "Invalid email.";
if (formData.message.length < 10) newErrors.message = "Message is too short.";
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
Then, modify the handleSubmit function to incorporate this validation:
const handleSubmit = (e) => {
e.preventDefault();
if (validateForm()) {
console.log(formData);
setFormData({ name: '', email: '', message: '' });
}
};
Boost Form Security: reCAPTCHA Integration Guide
A form is the place where usually a website takes input from the user and pass it to backend to process or store. So it is very vulnerable to have an attack from hackers or spammers. Also web scrapping bots uses form to collect informations. So as a developer, you should always have a proper security to protect your forms. Adding recaptcha to your forms will help you in that process. In this article, we will see how we can integrate recaptcha in a react form.
- What is CAPTCHA or reCAPTCHA?
CAPTCHA stands for Completely Automated Public Turing test to tell Computers and Humans Apart. It is a process where some kind of challenge or logic is used to differentiate between a human and computer. You might have already seen in different websites while submitting something through a form, for example a puzzle is given you to solve or to identify an object or solve some mathematical problems. These are actually captcha, which is usually difficult for a bot to solve because they are random usually. For humans, it is easier to solve and pass on. reCAPTCHA is an advanced version of CAPTCHA developed by Google.
- How do I integrate reCAPTCHA in a react form?
Lets see an example that how we can integrate recapthca in a react form. Assume, you already have a react application with a form.
We will use a package called react-google-recaptcha. Lets install the package:
npm install react-google-recaptcha
After installation, this package provides a component called ReCAPTCHA which you will need to add in between your form scope. Here is an example:
import React, { useState } from 'react';
import ReCAPTCHA from 'react-google-recaptcha';
const MyForm = () => {
const [formData, setFormData] = useState({
// Your form fields
});
const [isVerified, setIsVerified] = useState(false);
const handleChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
const handleRecaptchaChange = (token) => {
setIsVerified(!!token);
};
const handleSubmit = (e) => {
e.preventDefault();
if (isVerified) {
// Proceed with form submission
console.log("Form submitted!");
} else {
// Display an error message or prevent form submission
console.log("Please verify reCAPTCHA first.");
}
};
return (
<form onSubmit={handleSubmit}>
{/* Your form fields */}
<ReCAPTCHA
sitekey="YOUR_RECAPTCHA_SITE_KEY"
onChange={handleRecaptchaChange}
/>
<button type="submit" disabled={!isVerified}>Submit</button>
</form>
);
};
export default MyForm;
Note: you can see, this ReCAPTCHA component accepts a function on change, which is handleRecaptchaChange. When your captcha validation is successful, the function is triggered and a token is passed to the function. We have by default kept the form submission button as disabled, to let the user to first verify captcha before submitting. We have used a state as flag, which by default is false, and controlling the submit button with this state. So that means, when your validation is successful, we are setting the state isVerified as true, and submit button becomes active. Thus, we can use captcha validation to control form submission.
- Where would I get sitekey?
Ok, you have already noticed that the ReCAPTCHA component need a sitekey to function. Lets see how we can generate sitekey for production.
- Generating sitekey for production
Lets follow these steps for getting a site key:
1. Please go to this url and log in using your google account:
2. You will have to register a new site. Please enter the details as it requires, the label, reCAPTCHA type and your domain:
3. Click on submit, you should get two parameters, SITE KEY and SECRET KEY. Copy these values for future reference.
- Generating sitekey for localhost
If you are testing your application in local, you might want to use localhost or 127.0.0.1 as your domain. Google used to support these in past, but not anymore. For testing captcha in localhost you can use these codes as test SITE KEY & SECRET KEY.
Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI
Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe
- Add site key and test
Now you can use this site key in the ReCAPTCHA component and test the form. It should show you a captcha validation added to your react form.
Using recaptcha is very essential to integrate if you dont use any other security measures in your forms. As you can see, adding a recaptcha validation is very simple and easy to setup.
So now you are good to go with a basic form for your react project. There are plenty of stuffs to discuss apart from these essential topics, like react hooks, form validation libraries, managing centralizes state for all components, which all we will be exploring one by one later. But today, thats all from this article. Feel free to have your valued comments down here.
Have a great day.
Comments