React Captcha - JavaScript Exercise #20

React Captcha - JavaScript Exercise #20

Building a Simple Captcha Component in React

ยท

5 min read

Overview

In this exercise, you will build a simple captcha component in React. A captcha is a type of challenge-response test used in computing to determine whether or not the user is human. The captcha will consist of a mathematical expression that the user must solve to prove their humanity.

Instructions

  1. Create a new component called Captcha in your project.

  2. In the Captcha component, generate a random mathematical expression consisting of two numbers and an operator (+, -, *).

  3. Display the mathematical expression to the user in a div or span element.

  4. Provide an input field for the user to enter their answer.

  5. Upon submitting the answer, check if it is correct and display a success or error message accordingly.

Bonus Requirements

  • Implement a refresh button that generates a new mathematical expression.

  • Add a timer that resets the captcha after a certain amount of time.

  • Style the component to make it visually appealing.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Captcha exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the Captcha exercise

import React, { useState } from "react";

const operators = ["+", "-", "*"];

const generateRandomNumber = () => {
  return Math.floor(Math.random() * 10) + 1;
};

const generateRandomOperator = () => {
  const index = Math.floor(Math.random() * 3);
  return operators[index];
};

const generateCaptcha = () => {
  const number1 = generateRandomNumber();
  const number2 = generateRandomNumber();
  const operator = generateRandomOperator();
  const expression = `${number1} ${operator} ${number2}`;
  const answer = eval(expression);
  return { expression, answer };
};

const Captcha = () => {
  const [captcha, setCaptcha] = useState(generateCaptcha());
  const [inputValue, setInputValue] = useState("");
  const [message, setMessage] = useState("");

  const handleChange = (event) => {
    setInputValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (parseInt(inputValue) === captcha.answer) {
      setMessage("Success!");
      setCaptcha(generateCaptcha());
    } else {
      setMessage("Error. Please try again.");
    }
    setInputValue("");
  };

  const handleRefresh = () => {
    setCaptcha(generateCaptcha());
    setMessage("");
  };

  return (
    <div>
      <h1>Captcha</h1>
      <p>{captcha.expression}</p>
      <form onSubmit={handleSubmit}>
        <label>
          Answer:
          <input type="text" value={inputValue} onChange={handleChange} />
        </label>
        <button type="submit">Submit</button>
        <button type="button" onClick={handleRefresh}>
          Refresh
        </button>
      </form>
      {message && <p>{message}</p>}
    </div>
  );
};

export default Captcha;
import React from "react";
import Captcha from "./Captcha";

function App() {
  return (
    <div>
      <Captcha />
    </div>
  );
}

export default App;

Captcha is important because it helps protect websites and online services from spam, bots, and other automated attacks. Captchas are designed to verify that a user is a human and not a machine, by presenting a task that is easy for humans to complete but difficult for automated programs to solve.

Some of the main reasons why a captcha is important:

  1. Preventing spam: Captchas can prevent spam messages from being sent through contact forms, comment sections, and other online forms that require user input.

  2. Protecting user accounts: Captchas can prevent automated attacks that attempt to guess passwords, brute force login attempts, or steal personal information.

  3. Enhancing security: Captchas can help prevent automated attacks that exploit vulnerabilities in websites or online services, such as cross-site scripting (XSS) or SQL injection attacks.

  4. Improving user experience: Although captchas can sometimes be frustrating for users, they can help ensure that online services remain reliable and secure for all users.

There are several different types of captchas available, each with their own strengths and weaknesses. Here are some examples of different types of captchas:

  1. Image-based Captchas: These captchas require users to identify and select specific images from a set of images, such as selecting all the images that contain a specific object or animal. This type of captcha is commonly used on websites that require user registration or verification and can be effective at preventing automated attacks.

  2. Audio Captchas: Audio captchas require users to listen to a sequence of spoken words or numbers and enter them into a text field. This type of captcha is designed for users who may have difficulty with visual captchas, such as those with visual impairments or dyslexia.

  3. Text-based Captchas: Text-based captchas require users to enter a sequence of letters and/or numbers into a text field. These captchas can be presented in various forms, such as distorted letters or letters embedded in an image. They are commonly used on websites that require user registration or comment submission.

  4. Math Captchas: Math captchas require users to solve a simple math problem, such as addition or multiplication, and enter the result into a text field. This type of captcha is commonly used on websites that require user registration or comment submission.

  5. ReCaptcha: ReCaptcha is a type of captcha developed by Google that uses advanced algorithms to analyze user behavior and determine whether or not they are human. This captcha may present users with a simple task, such as clicking a checkbox or solving a math problem or may analyze user behavior in the background to determine whether or not they are human. ReCaptcha is widely used on websites and online services to prevent automated attacks and protect against spam and other malicious activity.

Overall, a captcha is an important tool for improving the security and reliability of websites and online services and is used widely across the internet to help protect against spam, bots, and other automated attacks.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.

ย