Build a Captcha Generator Using ReactJs
Last Updated :
02 Aug, 2024
A CAPTCHA generator is a tool that creates random and visually distorted text, requiring user input to prove they are human. It prevents automated bots from accessing websites or services by testing human comprehension. Our Captcha generator geĀnerates random text-baseĀd captchas that users must accurately input in order to process, effectively ensuring human interaction. In this article, we will create a Captcha Generator using React.
Preview Image:

Prerequisites
Steps to Create React Native Application
Step 1: Create a react native application by using this command
npx create-expo-app CaptchaGeneratorApp
Step 2: After creating your project folder, i.e. CaptchaGeneratorApp, use the following command to navigate to it
cd CaptchaGeneratorApp
Project Structure:
.png)
Approach / Functionalities:
In this approach,
- Random Character Generation: The application generates a CAPTCHA text by randomly selecting characters from three character sets: uppercase letters, lowercase letters, and numbers. This ensures that the CAPTCHA is a combination of various character types, making it more challenging for users to decipher.
- Random Shuffling: The generated text is randomly shuffled to increase complexity and prevent easy pattern recognition.
- Canvas Visualization: The CAPTCHA is dynamically drawn on an HTML canvas, creating a visual challenge for users to interpret.
- User Input Validation: Users must input their interpretation of the CAPTCHA text, which is then validated against the generated CAPTCHA.
- Feedback Messages: The application provides feedback messages, such as success or error, based on the accuracy of the user's input. A "Reload" button generates a new CAPTCHA for subsequent attempts.
Example: In this example, we'll use above explained approach
CSS
/*style.css*/
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
height: 100vh;
background: white;
}
.container {
width: 30rem;
background-color: #ffffff;
padding: 70px;
border-radius: 30px;
position: absolute;
transform: translate(-50%, -50%);
top: 45%;
left: 50%;
box-shadow: 0px 0px 30px 0px black;
}
.heading {
margin: 50px;
font-size: 30px;
text-align: center;
color: green;
}
.wrapper {
display: flex;
align-content: center;
justify-content: space-between;
margin: 1em 0;
}
canvas {
border: 2px solid crimson;
border-radius: 20px;
}
button#reload-button {
font-size: 26px;
width: 4.6em;
background-color: green;
cursor: pointer;
border: none;
border-radius: 0.4em;
color: #ffffff;
}
button#reload-button:hover {
background-color: rgb(46, 153, 46);
}
input[type='text'] {
font-family: 'Roboto Mono', monospace;
font-size: 1rem;
width: 100%;
padding: 16px;
border: 2px solid crimson;
border-radius: 20px;
}
button#submit-button {
width: 100%;
color: #ffffff;
font-size: 1.5em;
border: none;
margin-top: 1em;
padding: 0.8em 0;
border-radius: 0.4em;
background-color: green;
cursor: pointer;
}
button#submit-button:hover {
background-color: rgb(53, 175, 53);
}
JavaScript
//App.js
import React, { useState, useEffect, useRef } from 'react';
import './style.css';
function App() {
const [captchaText, setCaptchaText] = useState('');
const [userInput, setUserInput] = useState('');
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
initializeCaptcha(ctx);
}, []);
const generateRandomChar = (min, max) =>
String.fromCharCode(Math.floor
(Math.random() * (max - min + 1) + min));
const generateCaptchaText = () => {
let captcha = '';
for (let i = 0; i < 3; i++) {
captcha += generateRandomChar(65, 90);
captcha += generateRandomChar(97, 122);
captcha += generateRandomChar(48, 57);
}
return captcha.split('').sort(
() => Math.random() - 0.5).join('');
};
const drawCaptchaOnCanvas = (ctx, captcha) => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const textColors = ['rgb(0,0,0)', 'rgb(130,130,130)'];
const letterSpace = 150 / captcha.length;
for (let i = 0; i < captcha.length; i++) {
const xInitialSpace = 25;
ctx.font = '20px Roboto Mono';
ctx.fillStyle = textColors[Math.floor(
Math.random() * 2)];
ctx.fillText(
captcha[i],
xInitialSpace + i * letterSpace,
// Randomize Y position slightly
Math.floor(Math.random() * 16 + 25),
100
);
}
};
const initializeCaptcha = (ctx) => {
setUserInput('');
const newCaptcha = generateCaptchaText();
setCaptchaText(newCaptcha);
drawCaptchaOnCanvas(ctx, newCaptcha);
};
const handleUserInputChange = (e) => {
setUserInput(e.target.value);
};
const handleCaptchaSubmit = () => {
if (userInput === captchaText) {
alert('Success');
} else {
alert('Incorrect');
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
initializeCaptcha(ctx);
}
};
return (
<div>
<h2 className="heading">
Captcha Generator Using React
</h2>
<div className="container">
<div className="wrapper">
<canvas ref={canvasRef}
width="200"
height="70">
</canvas>
<button id="reload-button" onClick={
() => initializeCaptcha(
canvasRef.current.getContext('2d'))}>
Reload
</button>
</div>
<input
type="text"
id="user-input"
placeholder="Enter the text in the image"
value={userInput}
onChange={handleUserInputChange}/>
<button id="submit-button"
onClick={handleCaptchaSubmit}>
Submit
</button>
</div>
</div>
);
}
export default App;
Steps to Run:
To run react native application use the following command:
npm start
Output:
Similar Reads
Create a meme generator by using ReactJS In this tutorial, weâll create a meme generator using ReactJS. In the meme generator, we have two text fields in which we enter the first text and last text. After writing the text when we click the Gen button, it creates a meme with an image and the text written on it. Preview Image: meme generator
3 min read
Build a Random Name Generator using ReactJS In this article, a Random Name GeÂnerator will be created using React.js. Building a Random Name Generator means creating a program or application that generates random names, typically for various purposes like usernames, fictional characters, or data testing. It usually involves combining or selec
4 min read
Build a Password Manager using React Password manager using React js provides a secure and user-frieÂndly environment for users to store and manage their credeÂntials. It offers convenient feÂatures like adding, editing, and deÂleting password entries. The user can show/hide their password by clicking on a particular button. Preview o
6 min read
Create a QR code generator app using ReactJS In this article, we will create a simple QR Code generator app. A QR code is a two-dimensional barcode that can be read by smartphones. It allows the encoding of more than 4,000 characters in a compact format. QR codes can be used for various purposes, such as displaying text to users, opening URLs,
3 min read
Build a Captcha Generator in Tailwind CSS A Captcha Generator in Tailwind CSS is a tool that creates visual puzzles to distinguish between humans and bots on websites. It uses the Tailwind CSS framework to style the elements of the Captcha, making it visually appealing and user-friendly. This generator can help website owners protect their
3 min read
Build a Random User Generator App Using ReactJS In this article, we will create a random user generator application using API and React JS. A Random User Generator App Using React Js is a web application built with the React.js library that generates random user profiles. It typically retrieves and displays details like names, photos, and contact
4 min read