Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Build a Password Manager using React
Next article icon

Build a Captcha Generator Using ReactJs

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

gfg

Prerequisites

  • Introduction to React Native
  • React Native Components
  • React Hooks
  • Node.js and npm

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,

  • 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:


Next Article
Build a Password Manager using React
author
saurabhkumarsharma05
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • Geeks Premier League 2023

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: PrerequisiteTh
    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
  • ReactJS Calculator App (Building UI)
    We created our first app and deleted all those files we did not need, and created some of the files that we will need in the future. Now as we stand in our current situation we have a blank canvas before us where we will have to create our calculator app. We will be creating the project in multiple
    4 min read
  • Captcha Generator using HTML CSS and JavaScript
    A captcha is a way of identifying a user whether the user is human or not. A captcha is made up with the help of combining letters and digits. it ensures that the user who is trying to access the platform is a human. So without wasting the time let's get started. Application of CaptchaForm Authentic
    3 min read
  • Build a Anagram Checker App Using ReactJS
    In this article, we will create an Anagram Checker App using React. Anagrams are­ words or phrases that can be formed by re­arranging the letters of anothe­r word or phrase, using each lette­r exactly once. This app will enable users to enter two words or phrase­s and determine if they are anagrams
    4 min read
  • BMI Calculator Using React
    In this article, we will create a BMI Calculator application using the ReactJS framework. A BMI calculator determines the relationship between a person's height and weight. It provides a numerical value that categorizes the individual as underweight, normal weight, overweight, or obese. Output Previ
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences