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.

Categories
React Projects

Create a Coin Flip App 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 coin flip 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 coin-flip

with NPM to create our React project.

Create the Coin Flip App

To create the coin flip app, we write:

import React, { useMemo, useState } from "react";
const faces = ["heads", "tails"];

export default function App() {
  const [selectedFace, setSelectedFace] = useState("");
  const [coinFlipResult, setCoinFlipResult] = useState("");

  const flip = () => {
    let index;
    if (Math.random() < 0.5) {
      index = 0;
    } else {
      index = 1;
    }
    setCoinFlipResult(faces[index]);
  };

  const computerSelectedFace = useMemo(() => {
    const face = faces.find((f) => f !== selectedFace);
    return face;
  }, [selectedFace]);

  const isWin = useMemo(() => {
    return coinFlipResult === selectedFace;
  }, [coinFlipResult, selectedFace]);

  const showResult = () => {
    if (isWin) {
      return <p>you win</p>;
    }
    return <p>you lost</p>;
  };

  return (
    <div>
      <div>
        <h1>select a face</h1>
        <button onClick={() => setSelectedFace("heads")}>heads</button>
        <button onClick={() => setSelectedFace("tails")}>tails</button>
      </div>
      <p>you selected: {selectedFace}</p>
      <p>computer selected: {computerSelectedFace}</p>
      <button onClick={flip}>flip coin</button>
      {showResult()}
    </div>
  );
}

We first create the faces array which has the 'heads' and 'tails' values that we can pick from.

Then we define the selectedFace and coinFlipResult states to set the selected coin face and the coin flip result respectively.

Next, we have the flip function to call setCoinFlipResult to set the coin flip result.

We do that by picking a value from the faces array randomly.

Next, we define the computerSelectedFace with the useMemo hook.

The callback just picks the face that hasn’t been picked by the player.

We watch the selectedFace value to see which one to pick.

The isWin variable checks if coinFlipResult is the same as selectedFace to determine if the player wins.

Then we have the showResult to return the result to show to the player.

Below that, we have buttons to let the player pick heads or tails when we click them.

Then we show what the player and the computer selected.

And below that, we have the flip coin button to pick the coin face.

And below that, we call showResult to show the result.

Conclusion

We can create a coin flip game easily with React and JavaScript.

Categories
React Projects

Create a Welcome Message App 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 welcome message 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 welcome-message

with NPM to create our React project.

Create the Welcome Message App

To create the welcome message app, we write:

import React, { useState } from "react";

export default function App() {
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [message, setMessages] = useState("");

  const submit = (e) => {
    e.preventDefault();
    const formValid = firstName.length > 0 && lastName.length > 0;
    if (!formValid) {
      return;
    }
    setMessages(`hello, ${firstName} ${lastName}`);
  };

  return (
    <div>
      <form onSubmit={submit}>
        <div>
          <label>first name</label>
          <input
            value={firstName}
            onChange={(e) => setFirstName(e.target.value)}
          />
        </div>
        <div>
          <label>last name</label>
          <input
            value={lastName}
            onChange={(e) => setLastName(e.target.value)}
          />
        </div>
        <button type="submit">submit</button>
      </form>
      {message}
    </div>
  );
}

We have the firstName , lastName , message states, which holds the first name, last name, and the welcome message respectively.

Then we define the submit function to let us put the firstName and lastName into the message .

In it, we call e.preventDefault() to let us do client-side form submission.

Then we check if firstName and lastName are longer than 0 length.

If they are, then we call setMessages to set the message value to the welcome message.

Below that, we have the form with the onSubmit prop set to submit so we can run it with we click on a button with type submit .

Inside it, we have 2 inputs to let us enter the first and last name.

value has the value set in the state.

onChange is set to a function to set the firstName and lastName states respectively to functions that call setFirstName and setLastName respectively.

e.target.value has the value we typed in.

Below the form, we show or welcome message.

Conclusion

We can create a welcome message app with React and JavaScript.

Categories
React Projects

Create a Hangman 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 hangman 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 hangman

with NPM to create our React project.

Create the Hangman Game

To create the hangman game, we write:

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

export default function App() {
  const [answer] = useState("hangman");
  const [guesses, setGuesses] = useState([]);
  const [guessLetter, setGuessLetter] = useState("");
  const guessesLeft = useMemo(() => {
    return (
      6 -
      guesses.filter((g) => {
        return !answer.includes(g);
      }).length
    );
  }, [answer, guesses]);

  const lettersToShow = useMemo(() => {
    return answer.split("").map((a) => {
      if (guesses.includes(a)) {
        return a;
      }
      return "_";
    });
  }, [answer, guesses]);

  const isWin = useMemo(() => {
    const includedLetters = guesses.filter((g) => {
      return answer.includes(g);
    });
    return answer.split("").every((a) => {
      return includedLetters.includes(a);
    });
  }, [answer, guesses]);

  const guess = (e) => {
    e.preventDefault();
    const formValid = /[a-z]{1}/.test(guessLetter);
    if (!formValid) {
      return;
    }
    setGuesses((guesses) => [...guesses, guessLetter]);
    setGuessLetter("");
  };

  const reset = () => {
    setGuesses([]);
    setGuessLetter("");
  };

  if (isWin) {
    return (
      <div className="App">
        you win
        <button type="button" onClick={reset}>
          reset
        </button>
      </div>
    );
  } else {
    if (guessesLeft > 0) {
      return (
        <div>
          <p>guesses left: {guessesLeft}</p>
          <form onSubmit={guess}>
            <div>
              <label>guess</label>
              <input
                value={guessLetter}
                onChange={(e) => setGuessLetter(e.target.value)}
              />
            </div>
            <button type="submit">guess</button>
          </form>
          {lettersToShow.map((l, i) => {
            return <span>{l}</span>;
          })}
        </div>
      );
    } else {
      return (
        <div>
          you lost
          <button type="button" onClick={reset}>
            reset
          </button>
        </div>
      );
    }
  }
}

The answer state has the right answer.

guesses has an array of letters we’ve guessed.

guessLetter has the letter we typed into the guess input.

Next, we create a few variables with useMemo .

We compute the guessesLeft in the callback by subtracting the number of guessed letters that aren’t in the answer word from 6.

We watch answer and guesses so that the returned value will be updated whenever they’re updated.

Likewise, we create the lettersToShow state by splitting the answer into letters.

Then if the guessed letter is in answer , we return the letter.

Otherwise, we return an underscore.

This lets us display what’s guessed correctly so far.

The isWin variable has a boolean value to indicate whether the player won or not.

We create includedLetters to get the letters that has the letters in the guesses array that are included in answer .

And we return the if every letter in includedLetters are in the split answer string.

This lets the player know whether all the letters in the answer word has been guessed.

The guess function lets the player enter the guess.

In it, we call e.preventDefault() to do client-side submission.

Then we check if the player entered a letter into the input box before append the guessed letter to the guesses array.

To do that, we call setGuesses with a callback that returns an array with the existing guesses and the guessLetter with the latest letter guessed.

We also set setGuessLetter to an empty string to empty the input box.

The reset function reset guesses and guessLetter to their original values.

Then we check is isWin is true .

If it is, then we render the ‘you win’ message and a reset button.

The button calls reset when we click it.

Otherwise, if guessLeft is bigger than 0, this means the player can keep guessing.

We render the guessesLeft value and the form.

In the form, we render an input to set guessLetter .

The onChange prop has a function that gets the e.target.value , which has the inputted value, to set it.

The guess function is run when we click guess because of the onSubmit prop.

Below that, we display the lettersToShow .

In the eise block, we show ‘you lost’ ti the player is guessesLeft is 0, which means no more guesses are left.

We also show the reset button there.

Conclusion

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

Categories
React Projects

Create a Notes App 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 notes 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 notes

with NPM to create our React project.

We also need to add the uuid library to assign a unique ID to each note entry.

To install it, we run:

npm i uuid

Create the Notes App

To create the notes app, we write:

import React, { useMemo, useState } from "react";
import { v4 as uuidv4 } from "uuid";

export default function App() {
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [keyword, setKeyword] = useState("");
  const [notes, setNotes] = useState([]);

  const add = (e) => {
    e.preventDefault();
    setNotes((notes) => [
      ...notes,
      {
        id: uuidv4(),
        title,
        description
      }
    ]);
  };

  const remove = (index) => {
    setNotes((notes) => notes.filter((_, i) => i !== index));
  };

  const filteredNotes = useMemo(() => {
    if (!keyword) {
      return notes;
    }
    return notes.filter(({ title, description }) => {
      return title.includes(keyword) || description.includes(keyword);
    });
  }, [keyword, notes]);

  return (
    <div>
      <form onSubmit={add}>
        <h1>add note</h1>
        <div>
          <label>title</label>
          <input value={title} onChange={(e) => setTitle(e.target.value)} />
        </div>
        <div>
          <label>description</label>
          <input
            value={description}
            onChange={(e) => setDescription(e.target.value)}
          />
        </div>
        <button type="submit">add</button>
      </form>

      <form>
        <h1>search</h1>
        <div>
          <label>keyword</label>
          <input value={keyword} onChange={(e) => setKeyword(e.target.value)} />
        </div>
      </form>
      {filteredNotes.map((note, index) => {
        return (
          <div key={note.id}>
            <h2>{note.title}</h2>
            <p>{note.description}</p>
            <button type="button" onClick={() => remove(index)}>
              remove
            </button>
          </div>
        );
      })}
    </div>
  );
}

We have the title , description , keyword , and notes states.

title and description have the content for the notes.

keyword is the keyword for searching the notes.

We create them all with the useState hook.

Then we add the add function to add a note.

We call e.preventDefault to do client-side form submission.

Then we call setNotes to add the note entry to the notes array.

We do this by passing in a callback to the setNotes function.

We get the notes value from the callback parameter, then we return an array with the entry added to the end.

We call uuidv4 to assign the unique ID for the entry.

Next, we create the remove function to get the index and call setNotes with a callback to remove the entry.

In the callback, we call filter to return a notes array without the given index .

Then we define the filteredNotes variable with the useMemo hook to return the notes array filtered by keyword .

The 2nd array has the values to watch for in order for the returned value to update.

Below that,. we have the form with the onSubmit prop that’s triggered by the button with type submit ,

The inputs set the title and description respectively.

value are set to the states. And onChange set the title and description states with a function.

e.target.value has the inputted value.

Likewise, we have similar inputs for the 2nd form.

Then finally, we rendered the filteredNotes into divs.

We set the key prop to a unique ID.

And each div has a button that calls remove when we click the remove button.

Conclusion

We can create a notes app easily with React and JavaScript.