Open In App

Build a Captcha Generator Using ReactJs

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:

Approach / Functionalities:

In this approach,

Example: In this example, we’ll use above explained approach




//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;




/*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);
}

Steps to Run:

To run react native application use the following command:

npm start

Output:


Article Tags :