React Captcha – JavaScript Exercise #20

Overview

In this exercise, you will build a simple captcha component in React. Computing systems use captchas as challenge-response tests to determine whether users are human. The captcha will consist of a mathematical expression that the user must solve to prove their humanity.

Instructions for React Captcha

  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 React 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 confirm users are humans by using tasks that are easy for people but hard for bots.

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.

Use Cases

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. Websites that require user registration or verification commonly use this type of captcha and can effectively prevent 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. We designed this type of captcha 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 prompt users to solve simple arithmetic and input the answer. Websites that require user registration or comment submission commonly use this type of captcha.
  5. ReCaptcha: Google developed ReCaptcha, a type of captcha 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. Websites and online services widely use ReCaptcha to prevent automated attacks and protect against spam and other malicious activity.

Conclusion

Organizations widely use captchas to enhance website security and defend against automated attacks.

Additionally, thank you 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!

Boost your React skills with 25 React JavaScript Practice Exercises with Solutions hands-on challenges to master components, hooks, and more!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top