How to create captcha in react js?
November 15, 2024Hi Friends π,
Welcome To aHoisting!
To create captcha in react js, you have to use Canvas
to create a captcha. It will create captcha in react js.
Today, I am going to show you, how to create captcha in react js.
Table of contents
- Install and create a new React app.
- Import react component.
- Create a Component.
Letβs start with the first step.
Step 1: Install and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import react component.
After installing, you have to import your React component.
import React from 'react';
import Captcha from './Captcha';
import React, { useState, useRef, useEffect } from 'react';
import "./App.css";
Step 3: Create a Component.
You can use className="captcha"
to create captcha in react js.
<div className="captcha">
<canvas ref={canvasRef} width={150} height={50} style={{ border: '1px solid #ddd' }}></canvas>
<div>
<button onClick={refreshCaptcha}>Refresh</button>
</div>
<input
type="text"
placeholder="Enter CAPTCHA"
value={userInput}
onChange={handleInputChange}
/>
<button onClick={verifyCaptcha}>Verify</button>
{isVerified && <p>Verified!</p>}
</div>
Create captcha example.
The below code is an example of a React. You have to import './Captcha'
and use Canvas
to create a captcha to create captcha in react js.
App.js
import React from 'react';
import Captcha from './Captcha';
function App() {
return (
<div className="App">
<h1>React CAPTCHA</h1>
<Captcha />
</div>
);
}
export default App;
App.css
.captcha {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
.captcha canvas {
margin-bottom: 10px;
}
.captcha input {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
.captcha button {
padding: 8px 16px;
margin-top: 5px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.captcha button:hover {
background-color: #0056b3;
}
Captcha.js
import React, { useState, useRef, useEffect } from 'react';
import "./App.css";
const Captcha = () => {
const [captchaText, setCaptchaText] = useState('');
const [userInput, setUserInput] = useState('');
const [isVerified, setIsVerified] = useState(false);
const canvasRef = useRef(null);
// Generate a random CAPTCHA text
const generateCaptchaText = () => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let text = '';
for (let i = 0; i < 6; i++) {
text += chars.charAt(Math.floor(Math.random() * chars.length));
}
return text;
};
// Draw the CAPTCHA text on canvas
const drawCaptcha = (text) => {
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
// Set random font style and size
ctx.font = '24px Arial';
ctx.fillStyle = '#333';
// Draw the text with some distortion
ctx.setTransform(1, 0.3, Math.random() * 0.3, 1, 0, 0); // Distort the text
ctx.fillText(text, 10, 30); // Draw text at a position
ctx.setTransform(1, 0, 0, 1, 0, 0); // Reset transform
// Optionally, add some random lines for complexity
for (let i = 0; i < 4; i++) {
ctx.beginPath();
ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
ctx.strokeStyle = '#888';
ctx.lineWidth = 1;
ctx.stroke();
}
};
// Initialize CAPTCHA when the component mounts
useEffect(() => {
refreshCaptcha();
}, []);
// Generate new CAPTCHA text and draw it
const refreshCaptcha = () => {
const newCaptchaText = generateCaptchaText();
setCaptchaText(newCaptchaText);
drawCaptcha(newCaptchaText);
setUserInput('');
setIsVerified(false);
};
// Handle user input change
const handleInputChange = (e) => {
setUserInput(e.target.value);
};
// Verify if user input matches the CAPTCHA text
const verifyCaptcha = () => {
if (userInput === captchaText) {
setIsVerified(true);
alert('CAPTCHA Verified!');
} else {
alert('Incorrect CAPTCHA. Try again.');
refreshCaptcha();
}
};
return (
<div className="captcha">
<canvas ref={canvasRef} width={150} height={50} style={{ border: '1px solid #ddd' }}></canvas>
<div>
<button onClick={refreshCaptcha}>Refresh</button>
</div>
<input
type="text"
placeholder="Enter CAPTCHA"
value={userInput}
onChange={handleInputChange}
/>
<button onClick={verifyCaptcha}>Verify</button>
{isVerified && <p>Verified!</p>}
</div>
);
};
export default Captcha;
In the above code example, I have used the Canvas
to create captcha in react js.
Check the output of the above code.
All the best π