Categories
React Projects

Create a Memory Game with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a memory game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app memory-game

with NPM to create our React project.

Create the Memory Game

To create the memory game, we write:

import React, { useEffect, useState } from "react";
import { v4 as uuidv4 } from "uuid";
const answerArr = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
  .map((n) => {
    return {
      id: uuidv4(),
      open: false,
      value: n
    };
  })
  .sort(() => Math.random() - 0.5);

export default function App() {
  const [answer, setAnswer] = useState([...answerArr]);
  const [itemIds, setItemIds] = useState([]);

  const onClick = (id) => {
    if (!itemIds.includes(id)) {
      setItemIds((itemIds) => [...itemIds, id]);
    }
    const index = answer.findIndex((a) => a.id === id);
    setAnswer((answer) => {
      const ans = [...answer];
      ans[index].open = true;
      return ans;
    });
  };

  useEffect(() => {
    if (itemIds.length === 2) {
      const item1Index = answer.findIndex((a) => a.id === itemIds[0]);
      const item2Index = answer.findIndex((a) => a.id === itemIds[1]);
      if (answer[item1Index].value !== answer[item2Index].value) {
        setAnswer((answer) => {
          const ans = [...answer];
          ans[item1Index].open = false;
          ans[item2Index].open = false;
          return ans;
        });
      }
    }
  }, [itemIds, answer]);

  useEffect(() => {
    if (itemIds.length === 2) {
      setItemIds([]);
    }
  }, [itemIds]);

  return (
    <div>
      <style>
        {`
          .container {
            display: flex;
          }

.tile {
            border: 1px solid black;
            width: 20vw;
            height: 50px;
          }
          `}
      </style>
      <div className="container">
        {answer.map((a) => {
          return (
            <div key={a.id} className="tile" onClick={() => onClick(a.id)}>
              {a.open ? <div>{a.value}</div> : <div>&nbsp;</div>}
            </div>
          );
        })}
      </div>
    </div>
  );
}

We have the answerArr array which is a random array of numbers.

It’s used to render the boxes which the player can open by clicking.

If 2 numbers match, then they stay open.

Otherwise, both are closed.

Then we define the answer state with the answers.

itemIds have the IDs of the answer card that are open.

There can be max of 2 that are opened.

Next, we define the onClick which checks if itemIds includes id .

If it doesn’t we add it to the itemIds array with setItemIds .

Then we call setAnswer to set the item in answer that should be opened’s open property to true .

Next, we have a useEffect callback to check if itemIds.length is 2.

If it is, then we call findIndex to get the indexes of the answer items that we clicked on.

If their value s don’t match, then we close them by setting the open property of both items to false .

We watch the itemIds and answer values to do the update accordingly.

And we have another useEffect hook to check if itemIds.length is 2 again, but this time, if it’s true , when we set itemIds to an empty array.

Next, we add the styles for the cards in the style tag.

Then we render the answers items into divs.

We show the value is a.open is true .

Otherwise, we show an empty box.

Conclusion

We can create a memory game with React and JavaScript.

Categories
React Projects

Create a Magic 8 Ball with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a magic 8 ball app with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app magic-8-ball

with NPM to create our React project.

Create the Magic 8 Ball App

To create the magic 8 ball app, we write:

import React, { useState } from "react";
const answers = [
  "It is certain",
  "It is decidedly so",
  "Without a doubt",
  "Yes - definitely",
  "You may rely on it",
  "As I see it, yes",
  "Most likely",
  "Outlook good",
  "Yes",
  "Signs point to yes",
  "Don't count on it",
  "My reply is no",
  "My sources say no",
  "Outlook not so good",
  "Very doubtful",
  "Reply hazy, try again",
  "Ask again later",
  "Better not tell you now",
  "Cannot predict now",
  "Concentrate and ask again"
];

export default function App() {
  const [question, setQuestion] = useState("");
  const [answer, setAnswer] = useState("");

  const getAnswer = (e) => {
    e.preventDefault();
    if (!question) {
      return;
    }
    const index = Math.floor(Math.random() * answers.length);
    setAnswer(answers[index]);
  };

  return (
    <div>
      <style>
        {`
          .circle {
            border: 1px solid black;
            border-radius: 50%;
            width: 150px;
            height: 150px;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          `}
      </style>
      <form onSubmit={getAnswer}>
        <div>
          <label>question</label>
          <input
            value={question}
            onChange={(e) => setQuestion(e.target.value)}
          />
        </div>
        <button type="submit">get answer</button>
      </form>
      <div className="circle">
        <p>{answer}</p>
      </div>
    </div>
  );
}

We have the answers array with the answer items that can be chosen.

Then we define the question state which is set by entering the input.

And answer state is set by choosing an entry from the answers array randomly.

Then we gave the getAnswer function that picks the answer after the question is entered.

We call e.preventDefault() to do client-side submission.

We check if question is set.

And if it is, then we call setAnswer to set the answer .

Below that, we have a form with an input to let us enter the question value.

We get the value in the value prop and set the value with the onChange prop.

e.target.value has the inputted value.

answer has the answer that’s randomly chosen.

We put the answer in a circle by setting the className to circle .

Then we set the border-radius to 50% to make the div a circle.

Conclusion

We can create a magic 8 ball app easily with React and JavaScript.

Categories
React Projects

Create a Typing Test with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a typing test with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app typing-test

with NPM to create our React project.

Create the Typing Test

To create the typing test, we write:

import React, { useEffect, useMemo, useState } from "react";
const text =
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sit amet tellus tortor. ";

export default function App() {
  const [textToType] = useState(text);
  const [typedText, setTypedText] = useState("");
  const [timer, setTimer] = useState();
  const [elapsedMs, setElapsedMs] = useState(0);
  const [started, setStarted] = useState(false);
  const [wpm, setWpm] = useState(0);

  const parts = useMemo(() => {
    const splitTextToType = textToType.split("");
    let endIndexMatch = 0;
    for (const [index, s] of splitTextToType.entries()) {
      if (s !== typedText[index]) {
        endIndexMatch = index;
        break;
      }
    }
    return {
      matchedPart: textToType.slice(0, endIndexMatch),
      unmatchedPart: textToType.slice(endIndexMatch)
    };
  }, [textToType, typedText]);

  const start = () => {
    const timer = setInterval(() => {
      setElapsedMs((elapsedMs) => elapsedMs + 1);
      if (!started) {
        setStarted(true);
      }
    }, 1000);
    setTimer(timer);
  };

  const restart = () => {
    setStarted(started);
    setElapsedMs(0);
    setTypedText("");
  };

  useEffect(() => {
    if (parts.unmatchedPart.length === 1) {
      clearInterval(timer);
      setWpm(textToType.split(" ").length / (elapsedMs / (60 * 1000)));
    }
  }, [parts, textToType, timer, elapsedMs]);

  if (parts.unmatchedPart.length > 1) {
    return (
      <div>
        <div>
          <b>{parts.matchedPart}</b>
          {parts.unmatchedPart}
        </div>
        <button onClick={start}>start</button>
        <textarea
          disabled={!started}
          value={typedText}
          onChange={(e) => setTypedText(e.target.value)}
          style={{ width: "90vw", height: "300px" }}
        ></textarea>
      </div>
    );
  } else {
    return (
      <div>
        Your words per minute is {wpm}
        <button onClick={restart}>restart</button>
      </div>
    );
  }
}

We define the textToType state with the text we type in to finish the test.

typedText has the text we typed in.

timer has the timer for the typing test.

elaspedMs sets the elapsed time in milliseconds.

started sets whether the test has started.

wpm has the words per minute achieved.

Next we create the parts variable with the useMemo hook.

Its callback returns an object with the parts that we typed in and the parts we didn’t type yet.

matchedPart has the part we typed in.

unmatchedPart has the part we didn’t type in yet.

We get the matchedPart by computing the last index where the text we typed in matched what’s in the text string.

We split the textToType string and store it in splitTextToType

Then we loop through splitTextToType and get the first index of typedText that doesn’t match the splitTextToType array.

Next, we define the start function which starts the test.

We call setInterval to create the timer that sets the elaspedMs state.

It also sets the started state it’s set to false .

The callback runs every second.

We call setTimer to set the timer value.

The restart function just resets the values to the initial values.

In the useEffect callback, we check the parts.unmatchedPart property’s length and clear the timer with clearInterval is unmatchedPart is 1.

And we call setWpm to set the words per minute.

The 2nd array has the reactive states we’re watching and the callback runs whenever any of them changes.

Then we check if the test is finished with parts.unmatchedPart.length > 1 .

If parts.unmatchedPart.length > 1 is true , then the test isn’t finished so we render the typed and untyped text.

Then we render the button to let ys start the test.

And we have a text area to let the user type the test.

We disable the text area if started is false .

And we get and set the typed value with value and onChange .

Otherwise, the test is done and we show the words per minute and a button that we can click to restart the test.

Conclusion

We can create a typing test easily with React and JavaScript.

Categories
React Projects

Create a Dice Game with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a dice game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app dice-game

with NPM to create our React project.

Create the Dice Game

To create the dice game, we write:

import React, { useState } from "react";

export default function App() {
  const [rolledValue, setRolledValue] = useState(1);

  const roll = () => {
    setRolledValue(Math.ceil(Math.random() * 5 + 1));
  };

  return (
    <div>
      <button onClick={roll}>roll</button>
      <p>rolled dice value: {rolledValue}</p>
    </div>
  );
}

We have the rolledValue state that has the rolled dice’s value.

Then we create the roll function to set the rolledValue state to a random number.

Since Math.random only return a number between 0 and 1, we’ve to multiply the returned value by 5 and add 1 to generate a random number between 1 and 6.

Below that, we have a button that calls roll when we click it.

And we show the rolledValue below that.

Conclusion

We can create a dice game easily with React and JavaScript.

Categories
React Projects

Create a Rock Paper Scissors Game with React and JavaScript

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a rock paper scissors game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app rock-paper-scissors

with NPM to create our React project.

Create the Rock Paper Scissors Game

To create the rock paper scissors game, we write:

import React, { useMemo, useState } from "react";
const choices = ["rock", "paper", "scissors"];

export default function App() {
  const [selected, setSelected] = useState("");
  const [computedSelected, setComputedSelected] = useState("");

  const play = () => {
    if (!selected) {
      return;
    }
    const computerChoiceIndex = Math.floor(Math.random() * choices.length);
    setComputedSelected(choices[computerChoiceIndex]);
  };

  const result = useMemo(() => {
    if (computedSelected === selected) {
      return `it's a tie`;
    } else {
      if (
        (computedSelected === "rock" && selected === "scissors") ||
        (computedSelected === "paper" && selected === "rock") ||
        (computedSelected === "scissors" && selected === "paper")
      ) {
        return "computer won";
      }
      return "player won";
    }
  }, [computedSelected, selected]);

  return (
    <div>
      <div>
        <button onClick={() => setSelected("rock")}>rock</button>
        <button onClick={() => setSelected("paper")}>paper</button>
        <button onClick={() => setSelected("scissors")}>scissors</button>
      </div>
      <button onClick={play}>play</button>
      <p>your choice: {selected}</p>
      <p>computer's choice: {computedSelected}</p>
      <div>{result}</div>
    </div>
  );
}

We define the choices array with the choices to select from.

Then we define the selected state to hold the player’s choice.

And we define the computedSelected state to hold the computer’s choice.

Next, we define the play function to let the computer choose the choice.

We call setComputedSelected with a random choice to set the computer’s choice.

Then we define the result variable with the useMemo hook to get the compyterSelected and selected values to check who won.

If the values are the same, then it’s a tie.

Otherwise, rock beats scissors, paper beats rock, and scissors beats paper.

We pass in all the values we’re watching to compute the result in the 2nd argument.

After that. we add the buttons to let the player set the selected value.

Below that, we show the play button to run play when we click it.

Then we display the player’s and computer’s choice.

And finally, we display the result .

Conclusion

We can create a rock, paper, scissors game with React and JavaScript.