Categories
React Projects

Create a Height Converter 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 height converter 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 height-converter

with NPM to create our React project.

Create the Height Converter App

To create the height converter app, we write:

import React, { useState } from "react";

export default function App() {
  const [feet, setFeet] = useState(0);
  const [inches, setInches] = useState(0);
  const [centimeters, setCentimeters] = useState(0);

  const submit = (e) => {
    e.preventDefault();
    const formValid = +feet >= 0 && +inches >= 0;
    if (!formValid) {
      return;
    }
    setCentimeters((+feet + +inches / 12) * 12 * 2.54);
  };

  return (
    <div>
      <form onSubmit={submit}>
        <div>
          <label>feet</label>
          <input value={feet} onChange={(e) => setFeet(e.target.value)} />
        </div>
        <div>
          <label>inches</label>
          <input value={inches} onChange={(e) => setInches(e.target.value)} />
        </div>
        <button type="submit">calculate</button>
      </form>
      <p>{centimeters} cm</p>
    </div>
  );
}

We create the feet , inches and centimeters states with the useState hook.

Then we define the submit function to calculate the centimeters from feet and inches .

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

Then we check if feet and inches are valid numbers.

If they are, then we calculate the centimeters equivalent of the feet and inches and call setCentimeters to set the centimeter value.

Below that, we have the form.

We pass the submit function to the onSubmit hook to trigger submission when we click the calculate button.

The inputs are used to set feet and inches .

onChange is set to a function to set each value.

e.target.value has the inputted value.

Below that, we display the centimeters value.

Conclusion

We can create a height converter app easily with React and JavaScript.

Categories
React Projects

Create a Guess a Number 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 guess a number 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 guess-number-game

with NPM to create our React project.

Create the Guess a Number Game

To create the guess a number game, we write:

import React, { useState } from "react";

export default function App() {
  const [started, setStarted] = useState(false);
  const [status, setStatus] = useState(false);
  const [answer, setAnswer] = useState(0);
  const [rightAnswer, setRightAnsweer] = useState(0);
  console.log(rightAnswer);

  const submit = (e) => {
    e.preventDefault();
    const formValid = +answer >= 0;
    if (!formValid) {
      return;
    }
    if (+answer === +rightAnswer) {
      setStatus("you got it");
      setStarted(false);
    } else if (+answer < +rightAnswer) {
      setStatus("too low");
    } else {
      setStatus("too high");
    }
  };

  const start = () => {
    setRightAnsweer(Math.ceil(Math.random() * 10));
    setStarted(true);
  };

  if (started) {
    return (
      <div>
        <form onSubmit={submit}>
          <div>
            <label>answer</label>
            <input value={answer} onChange={(e) => setAnswer(e.target.value)} />
          </div>
          <button type="submit">check</button>
        </form>
        <p>{status}</p>
      </div>
    );
  } else {
    return (
      <div>
        <button type="button" onClick={start}>
          start
        </button>
        <p>{status}</p>
      </div>
    );
  }
}

We have the started state to set render the form to let us enter a number when the game is started.

status shows whether the guess is right or not.

answer shows the answer.

rightAnswer has the right answer.

Next, we have the submit function that checks the answer we entered.

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

Then we check if answer is bigger than or equal to 0.

If it is, then we check it against rightAnswer and set the status and started states accordingly.

The start function sets the rightAnswer with setRightAnswer .

setStarted sets the started state.

If started is true , we show the form.

We set the onSubmit prop to submit to let us submit our answer .

submit is run when we click on the check button, which has button type submit .

The input’s value is set to answer and we set answer with the onChange callback.

We get the inputted value with e.target.value .

Below the form, we show the status .

If started is false , we show the start button and the status .

Conclusion

We can create a guess a number game with React and JavaScript.

Categories
React Projects

Create a Balloon Popping 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 balloon popping 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 balloon-popping-game

with NPM to create our React project.

Create the Balloon Popping Game

To create the balloon popping game, we write:

import React, { useState } from "react";

const colors = ["red", "green", "blue"];

const generateColor = () => {
  const index = Math.floor(Math.random() * colors.length);
  return colors[index];
};

const balloonArr = Array(25)
  .fill()
  .map((_, i) => ({ id: i, popped: false, color: generateColor() }));

export default function App() {
  const [balloons, setBalloons] = useState(balloonArr);

  const onPop = (index) => {
    setBalloons((balloons) => {
      const b = [...balloons];
      b[index].popped = true;
      return b;
    });
  };

  return (
    <div className="App">
      <style>
        {`
        .balloon-container {
          display: inline-block;
        }

        .balloon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          border: 1px solid black;
        }
      `}
      </style>
      <div>
        {balloons.map((b, i) => {
          if (!b.popped) {
            return (
              <div className="balloon-container" key={b.id}>
                <div
                  className="balloon"
                  style={{ backgroundColor: b.color }}
                  onMouseOver={() => onPop(i)}
                ></div>
              </div>
            );
          } else {
            return <div className="balloon-container">popped</div>;
          }
        })}
      </div>
    </div>
  );
}

We have the colors array with the balloon colors.

generateColor picks a random color from the colors array.

Then we have the balloonArr array which has 25 objects with data for rendering the balloons.

It includes whether it’s popped or not, and the color .

In App , we have the balloons state which is set to balloonArr initially.

The onPop function lets us set the balloons entry with the given index ‘s popped property to true .

We have a callback to get the balloons , then we make a copy, modify it, and then return the modified copy.

Next, we have the styles to make the balloons display online.

The ballon class makes the div display as circles by setting the border-radius to 50% .

Then finally, we render the balloons by calling map .

In the map callback, we check if b.popped is false .

If it’s false , then we render the ballon with divs.

We set the styles and the onMouseOver prop to a function that calls the onPop function to pop the balloons by setting popped to true .

Otherwise, we render the ‘popped’ text.

Conclusion

We can create a balloon popping game with React and JavaScript.

Categories
React Projects

Create a Quiz 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 an addition 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 quiz-game

with NPM to create our React project.

Create the Quiz Game

To create the quiz game, we write:

import React, { useState } from "react";

const questions = [
  {
    question: "What is American football called in England?",
    choices: ["American football", "football", "Handball"],
    rightAnswer: "American football"
  },
  {
    question: "What is the largest country in the world?",
    choices: ["Russia", "Canada", "United States"],
    rightAnswer: "Russia"
  },
  {
    question: "What is the 100th digit of Pi?",
    choices: ["9", "4", "7"],
    rightAnswer: 9
  }
];

export default function App() {
  const [score, setScore] = useState(0);
  const [questionIndex, setQuestionIndex] = useState(0);
  const [answer, setAnswer] = useState("");

  const restart = () => {
    setScore(0);
    setAnswer("");
    setQuestionIndex(0);
  };

  const submit = (e) => {
    e.preventDefault();
    if (answer === questions[questionIndex].rightAnswer) {
      setScore((score) => score + 1);
    }

    if (questionIndex < questions.length) {
      setQuestionIndex((i) => i + 1);
    }
  };

if (questionIndex < questions.length) {
    return (
      <div>
        <label>{questions[questionIndex].question}</label>
        {questions[questionIndex].choices.map((c, i) => {
          return (
            <div>
              <input
                type="radio"
                name="choice"
                value={c}
                onChange={(e) => setAnswer(e.target.value)}
                checked={answer === c}
              />
              {c}
            </div>
          );
        })}
        <button type="button" onClick={submit}>
          check
        </button>
        <p>score: {score}</p>
      </div>
    );
  } else {
    return (
      <form>
        <div v-else>
          <button type="button" onClick={restart}>
            restart
          </button>
        </div>
        <p>score: {score}</p>
      </form>
    );
  }
}

We have the questions array with the question, choices, and rightAnswer properties with the question, the choices for the question, and the right answer for the question respectively.

Then in App , we have the score , questionIndex , and answer states created with useState .

answer is the answer the player chooses.

Below that, we have the submit function, we call e.preventDefault() to do client-side form submission.

Then we check if our answer choice is the same as rightAnswer .

If it is, then we call setScore to increment the score.

And if questionIndex is less than questions.length that means we have more questions to show.

Therefore, we call setQuestionIndex to increment the score with a callback that returns the original index i plus 1.

Next, we have an if statement that does the same check if the if in the submit function.

If questionIndex is less than questions.length , we should the question with the radio buttons for the player to choose the answer.

We set the checked prop to set the radio button to checked.

We determined which one if checked by comparing the answer value to c .

onChange lets us set the choice with a function that calls setAnswer to set the choice.

Below that, we display the check button that calls submit to submit the answer when we click it.

And then we show the score below that.

If the if condition is false , we show the restart button that calls restart to reset all the values.

And we also show the score below that.

Conclusion

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

Categories
React Projects

Create an Addition 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 an addition 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 addition-game

with NPM to create our React project.

Create the Addition Game

To create the addition game, we write:

import React, { useState } from "react";

export default function App() {
  const [num1, setNum1] = useState(0);
  const [num2, setNum2] = useState(0);
  const [sum, setSum] = useState(0);
  const [score, setScore] = useState(0);

  const generateQuestion = () => {
    setNum1(Math.ceil(Math.random() * 10));
    setNum2(Math.ceil(Math.random() * 10));
  };

  const submit = (e) => {
    e.preventDefault();
    const formValid = +sum >= 0;
    if (!formValid) {
      return;
    }
    if (+num1 + +num2 === +sum) {
      setScore((score) => score + 1);
    }
    generateQuestion();
  };

  return (
    <div className="App">
      <form onSubmit={submit}>
        <div>
          <label>
            {num1} + {num2}
          </label>
          <input value={sum} onChange={(e) => setSum(e.target.value)} />
        </div>

        <button type="submit">check</button>
      </form>
      <button type="button" onClick={generateQuestion}>
        start game
      </button>
      <p>score: {score}</p>
    </div>
  );
}

We have the num1 , num2 , sum , and score states created with the useState hook.

num1 and num2 are the parts of the addition question.

sum has the sum we enter.

score has the score.

Below that, we have the generateQuestion function to generate the num1 and num2 values.

We call

setNum1 and setNum2 to set them.

Math.random creates a random number between 0 and 1.

Math.ceil rounds up to the nearest integer.

Then we have the submit function that checks the sum value against the sum of num1 and num2 .

Before we do the check, we call e.preventDefault() so we can do client-side submission.

Then we check if sum is a number bigger than or equal to 0.

And if it is, then we do the check.

If the answer matches the sum, then we increase the score with setScore .

We increase it by passing a callback that returns the original score plus 1.

Then we call generateQuestion again to generate the next question.

Below that, we have a form that has the onSubmit prop.

onSubmit runs when we click on the check button.

In the form, we display num1 and num2 .

And we have an input that takes the sum value and we set sum by call setSum in the onChange callback.

e.target.value has the inputted value.

Below that, we have the start game button which calls generateQuestion when we click it.

And finally, we show the score below that.

Conclusion

We can create an addition game easily with React and JavaScript.