Build a Captcha Generator Using ReactJs Last Updated : 02 Aug, 2024 Summarize Comments Improve Suggest changes Share 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:PrerequisitesIntroduction to React NativeReact Native ComponentsReact HooksNode.js and npm Steps to Create React Native ApplicationStep 1: Create a react native application by using this commandnpx create-expo-app CaptchaGeneratorAppStep 2: After creating your project folder, i.e. CaptchaGeneratorApp, use the following command to navigate to itcd CaptchaGeneratorAppProject 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 startOutput: Comment More infoAdvertise with us S saurabhkumarsharma05 Follow Improve Article Tags : Project Web Technologies ReactJS Geeks Premier League Geeks Premier League 2023 +1 More Similar Reads Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav 11 min read Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De 5 min read React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications 15+ min read React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version 7 min read JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q 15+ min read Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We 9 min read Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w 8 min read Use Case Diagram - Unified Modeling Language (UML) A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within 9 min read HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML 14 min read Like