Write typing test module with a paragraph, timer, text accuracy, and result code in ReactJS



 import React, { useState, useEffect } from "react";

const TypingTest = () => {

  const [paragraph, setParagraph] = useState(

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed egestas lacus in enim congue, a commodo ipsum varius. Integer bibendum velit vel accumsan hendrerit. Nunc malesuada lacus vel velit facilisis consectetur. Sed bibendum erat euismod, fringilla nulla eu, tempor libero. Nam congue, magna id tincidunt feugiat, lectus eros blandit mi, sit amet congue ante odio a risus."

  );

  const [timer, setTimer] = useState(60);

  const [typing, setTyping] = useState("");

  const [accuracy, setAccuracy] = useState(0);

  const [result, setResult] = useState(null);

  let intervalId = null;


  useEffect(() => {

    if (typing === paragraph) {

      clearInterval(intervalId);

      setResult(

        `Finished! Your typing accuracy was ${accuracy.toFixed(2)}%.`

      );

    }

  }, [typing, accuracy]);


  useEffect(() => {

    intervalId = setInterval(() => {

      setTimer(timer - 1);

      if (timer === 0) {

        clearInterval(intervalId);

        setResult(

          `Time's up! Your typing accuracy was ${accuracy.toFixed(2)}%.`

        );

      }

    }, 1000);


    return () => {

      clearInterval(intervalId);

    };

  }, [timer, accuracy]);


  const handleTyping = (event) => {

    setTyping(event.target.value);

    setAccuracy(

      (event.target.value.split("").filter((c, i) => c === paragraph[i]).length /

        paragraph.length) *

        100

    );

  };


  return (

    <div>

      <p>{paragraph}</p>

      <textarea value={typing} onChange={handleTyping} />

      <p>Time remaining: {timer}</p>

      <p>Accuracy: {accuracy.toFixed(2)}%</p>

      <p>{result}</p>

    </div>

  );

};


export default TypingTest;




Explanations: This code creates a typing test module with a paragraph, timer, text accuracy, and result. The paragraph, timer, typing, accuracy, and result are stored in state variables. The useEffect hook is used to listen for changes in the typing and accuracy and update the result if necessary. The timer is displayed on the page and decrements every second using a setInterval function. When the timer reaches zero, the timer is cleared and the result is updated with the message "Time's up!". The text accuracy is calculated as the ratio of correct characters typed to the total number of characters in the paragraph and

Post a Comment

Previous Post Next Post
© 2023 Developed and Design By
NILESH NISHAD