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.

Categories
React Projects

Create a Contact Form 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 contact form 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 contact-form

with NPM to create our React project.

Create the Contact Form App

To create the contact form app, we write:

import React, { useState } from "react";

export default function App() {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [message, setMessage] = useState("");

  const submit = (e) => {
    e.preventDefault();
    const formValid =
      name.length > 0 &&
      /(.+)@(.+){2,}.(.+){2,}/.test(email) &&
      message.length > 0;
    if (!formValid) {
      return;
    }
    if (!localStorage.getItem("messages")) {
      localStorage.setItem("messages", JSON.stringify([]));
    }
    const messages = JSON.parse(localStorage.getItem("messages"));
    messages.push({
      name,
      email,
      message
    });
    localStorage.setItem("messages", JSON.stringify(messages));
  };

  const onReset = () => {
    setName("");
    setEmail("");
    setMessage("");
  };

  return (
    <div className="App">
      <form onSubmit={submit} onReset={onReset}>
        <div>
          <label>name</label>
          <input value={name} onChange={(e) => setName(e.target.value)} />
        </div>

        <div>
          <label>email</label>
          <input
            value={email}
            onChange={(e) => setEmail(e.target.value)}
          />
        </div>

        <div>
          <label>message</label>
          <textarea
            value={message}
            onChange={(e) => setMessage(e.target.value)}
          ></textarea>
        </div>

        <button type="submit">submit</button>
        <button type="reset">reset</button>
      </form>
    </div>
  );
}

We have the name , email , and message states created with the useState hook.

Then we create the submit function to let users submit the contact form.

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

Then we check if the values entered are valid.

And then we check is a local storage entry with key messages exists.

If it doesn’t exist, then we add a new entry with the message key.

Then we add a new entry to the JSON array with the key message into local storage.

We parse the JSON array string with JSON.parse .

Then we call push on the parsed array.

And then we call setItem to save the updated array.

Next, we define the onReset function to set all the state values to empty strings.

Then we add a form with inputs.

value prop has the inputted value from the state.

And the onChange prop of reach input is set to a function that gets the inputted value and set them as the value of various states.

The onSubmit prop is triggered when we click the submit button.

onReset is triggered when we click the reset button.

Conclusion

We can create a contact form easily with React and JavaScript.

Categories
React Projects

Create a Tip Calculator 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 tip calculator 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 tip-calculator

with NPM to create our React project.

Create the Tip Calculator App

To create the tip calculator app, we write:

import React, { useState } from "react";

export default function App() {
  const [percentageTip, setPercentageTip] = useState(0);
  const [billAmount, setBillAmount] = useState(0);
  const [tipAmount, setTipAmount] = useState(0);
  const [total, setTotal] = useState(0);

  const calculate = (e) => {
    e.preventDefault();
    const formValid = +billAmount > 0 && +percentageTip > 0;
    if (!formValid) {
      return;
    }
    const tipAmount = +billAmount * (+percentageTip / 100);
    const total = +billAmount * (1 + percentageTip / 100);
    setTipAmount(tipAmount);
    setTotal(total);
  };

  return (
    <div className="App">
      <form onSubmit={calculate}>
        <div>
          <label>bill amount</label>
          <input
            value={billAmount}
            onChange={(e) => setBillAmount(e.target.value)}
          />
        </div>
        <div>
          <label>percentage tip</label>
          <input
            value={percentageTip}
            onChange={(e) => setPercentageTip(e.target.value)}
          />
        </div>
        <button type="submit">calculate</button>
      </form>
      <p>tip amount: {tipAmount.toFixed(2)}</p>
      <p>total: {total.toFixed(2)}</p>
    </div>
  );
}

We have the percentageTip , billAmount , tipAmount , and total states in the App component.

We create them with the useState hook.

Then we define the calculate function.

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

Then we check billAmoubnt and percentageTip to see if they’re valid values.

If they are, then we calculate the tipAmount and total .

And we call setTipAmount and setTotal to set the values.

Below that, we have the form element with the onSubmit prop set to calculate so that it runs when we click the calculate button.

In the form, we have inputs to let us enter the bill amount and percentage tip.

value has the value from the states.

And we set the states with the function we pass into the onChange prop.

e.target.value gets the inputted value.

Below that, we display the tipAmount and total .

toFixed lets us round the numbers to the given amount of decimal places.

Conclusion

We can create a tip calculator easily with React and JavaScript.

Categories
React Projects

Create a Weight 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 weight 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 weight-converter

with NPM to create our React project.

Create the Weight Converter App

To create the weight converter app, we write:

import React, { useState } from "react";

export default function App() {
  const [weightInLb, setWeightInLb] = useState(0);
  const [weightInKg, setWeightInKg] = useState(0);

  const calculate = (e) => {
    e.preventDefault();
    const formValid = +weightInLb >= 0;
    if (!formValid) {
      return;
    }
    setWeightInKg(+weightInLb * 0.453592);
  };

  return (
    <div className="App">
      <form onSubmit={calculate}>
        <div>
          <label>weight in pounds</label>
          <input
            value={weightInLb}
            onChange={(e) => setWeightInLb(e.target.value)}
          />
        </div>
        <button type="submit">calculate</button>
      </form>
      <p>{weightInKg} kg</p>
    </div>
  );
}

We defined the weightInLb and weightInKg states with the useState hook.

Then we defined the calculate function to calculate the weightInKg value.

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

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

If it is, then we calculate the weightInKg value, which is the weightInLb value converter to kilograms.

In the return statement, we have a form that has the onSubmit prop which runs the calculate function when the submit event is triggered.

The submit event is triggered by clicking the calculate button.

The input in the form has the value prop to set the value of the input.

The onChange has a function that takes the inputted value and calls setWeightInLb to set the weightInLb value.

e.target.value has the inputted value.

Below the form, we show the weightInKg value.

Conclusion

We can create a weight converter easily with React and JavaScript.

Categories
React Projects

Create a BMI Calculator 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 BMI calculator 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 bmi-calculator

with NPM to create our React project.

Create the BMI Calculator App

To create the BMI calculator app, we write:

import React, { useState } from "react";

export default function App() {
  const [height, setHeight] = useState(0);
  const [mass, setMass] = useState(0);
  const [bmi, setBmi] = useState(0);

  const calculate = (e) => {
    e.preventDefault();
    const formValid = +height > 0 && +mass > 0;
    if (!formValid) {
      return;
    }
    const bmi = +mass / (+height) ** 2;
    setBmi(bmi);
  };

  return (
    <div className="App">
      <form onSubmit={calculate}>
        <div>
          <label>height in meters</label>
          <input value={height} onChange={(e) => setHeight(e.target.value)} />
        </div>

        <div>
          <label>mass in kg</label>
          <input value={mass} onChange={(e) => setMass(e.target.value)} />
        </div>

        <button type="submit">calculate</button>
      </form>
      <p>bmi: {bmi}</p>
    </div>
  );
}

First, we defined the height , mass and bmi states with the useState hook.

Then, we have the calculate function to calculate the bmi from the height and mass .

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

Then we check if height and mass are valid values.

If they are, then we calculate the bmi and call setBmi to set the BMI value.

Then we return a form with the onSubmit prop set to calculate .

It’s run when we click on the calculate button.

Also, we have 2 inputs that take the inputted value and set them as the value height and mass respectively.

e.target.value has the inputted value.

Below the form, we display the bmi .

Conclusion

We can create a BMI calculator easily with React and JavaScript.