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.

Categories
React Projects

Create a Countdown Timer 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 countdown timer 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 countdown-timer

with NPM to create our React project.

Create the Countdown Timer App

To create the countdown timer app, we write:

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

const futureDate = new Date(2050, 0, 1);
const getDateDiff = (date1, date2) => {
  const diff = new Date(date2.getTime() - date1.getTime());
  return {
    year: diff.getUTCFullYear() - 1970,
    month: diff.getUTCMonth(),
    day: diff.getUTCDate() - 1,
    hour: diff.getUTCHours(),
    minute: diff.getUTCMinutes(),
    second: diff.getUTCSeconds()
  };
};

const formatDate = (date) => {
  let d = new Date(date),
    month = (d.getMonth() + 1).toString(),
    day = d.getDate().toString(),
    year = d.getFullYear().toString();

  if (month.length < 2) month = "0" + month;
  if (day.length < 2) day = "0" + day;

  return [year, month, day].join("-");
};

export default function App() {
  const [diff, setDiff] = useState({});

  useEffect(() => {
    const timer = setInterval(() => {
      setDiff(getDateDiff(new Date(), futureDate));
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  return (
    <div className="App">
      <p>
        {diff.year} years, {diff.month} months, {diff.day} days,
        {diff.hour} hours, {diff.minute} minute, {diff.second} seconds until{" "}
        {formatDate(futureDate)}
      </p>
    </div>
  );
}

The futureDate variable is the date we’re counting down towards.

getDateDiff is a function that calculates the difference between 2 dates.

We compute that by subtracting the UNIX timestamps of date2 and date1 .

getTime gets the UNIX timestamp.

We pass that difference to the Date constructor to get the date difference object.

Then we get the parts of it with various methods.

getUTCFullYear gets the year. We’ve to subtract it by 1970 to get the difference.

getUTCMonth gets the month.

getUTCDate gets the date.

getUTCHours gets the hours.

getUTCMinutes gets the minutes.

getUTCSeconds gets the seconds.

The formatDate function formats the date .

We use it to format the futureDate to display it in a human-readable format.

We just get the year, month, and day, and join them with a dash.

In the App component, we call setInterval to call setDiff to set the date and time difference every second.

And we return a function that calls clearInterval when we unmount the component.

In the JSX code, we show the diff parts and the futureDate formatted with formatDate .

Conclusion

We can create a countdown timer easily with React and JavaScript.