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.

Categories
React Projects

Create a Digital Clock 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 digital clock 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 digital-clock

with NPM to create our React project.

Create the Digital Clock App

To create the digital clock app, we write:

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

const date = new Date();
export default function App() {
  const [dateTime, setDateTime] = useState({
    hours: date.getHours(),
    minutes: date.getMinutes(),
    seconds: date.getSeconds()
  });

  useEffect(() => {
    const timer = setInterval(() => {
      const date = new Date();

      setDateTime({
        hours: date.getHours(),
        minutes: date.getMinutes(),
        seconds: date.getSeconds()
      });
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  return (
    <div className="App">
      <div>
        {dateTime.hours}:{dateTime.minutes}:{dateTime.seconds}
      </div>
    </div>
  );
}

We have the date variable outside the App component to set the initial date.

Inside App , we have the dateTime state, which we create with the useState hook.

It’s set to an object with the hours , minutes , and seconds properties.

We get the hours, minutes, and seconds with getHours , getMinutes , and getSeconds respectively.

Then we add the useEffect hook to get the latest date and time assigned to the date variable.

We call setInterval to set the latest date and time every second as indicated by the 2nd argument.

Then we call setDateTime with the hours, minutes, and seconds values.

In the last line of the useEffect callback, we return a function that calls clearInterval with timer to clear the timer when we unmount the component.

In the JSX code, we display the hours, minutes, and seconds.

Conclusion

We can create a digital clock app with React and JavaScript easily.

Categories
React Projects

Create a Background Color Switcher App with Vue 3 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 background color switcher 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 background-color-switcher

with NPM to create our React project.

Create the Background Color Switcher App

To create the background color switcher app, we write:

import React, { useState } from "react";
const colors = ["red", "green", "blue", "yellow"];

export default function App() {
  const [backgroundColor, setBackgroundColor] = useState("");

  return (
    <div
      className="App"
      style={{
        backgroundColor
      }}
    >
      <style>
        {`
        .circle {
          border-radius: 50%;
          width: 50px;
          height: 50px;
          border: 1px solid black;
          display: inline-block;
          cursor: pointer;
        }

        #screen {
          width: 100vw;
          height: 100vh;
        }
      `}
      </style>
      {colors.map((c) => {
        return (
          <div
            key={c}
            style={{
              backgroundColor: c
            }}
            class="circle"
            onClick={() => setBackgroundColor(c)}
          ></div>
        );
      })}
    </div>
  );
}

We have the colors array with the colors we can switch to.

In App , we have the backgroundColor state which is used to set the background color of the wrapper div.

The style tag has the styles for the circles, which are divs we return in the map callback.

We can make a circle by setting border-radius to 50%.

Also, we set the border to make the circle edge appear.

We set cursor to pointer so that we see a hand when we hover over the circle.

In the colors.map callback, we return a div with the style with the backgroundColor set to the color c in the colors array.

And we have an onClick listener that calls setBackgroundColor to set the color.

Conclusion

We can add a background color switcher with React and JavaScript.

Categories
React Projects

Create a Quote of the Day App with Vue 3 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 quote of the day 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 quote-of-the-day

with NPM to create our React project.

Create the Quote of the Day App

To create the quote of the app, we write:

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

export default function App() {
  const [quoteOfTheDay, setQuoteOfTheDay] = useState("");
  const [quotes, setQuotes] = useState([]);

  const getQuotes = async () => {
    const res = await fetch(`https://type.fit/api/quotes`);
    const quotes = await res.json();
    setQuotes(quotes);
  };

  const getRandomQuote = () => {
    const index = Math.floor(Math.random() * quotes.length);
    setQuoteOfTheDay(quotes[index].text);
  };

  useEffect(() => {
    getQuotes();
  }, []);

  return (
    <div className="App">
      <button onClick={getRandomQuote}>get quote</button>
      <p>{quoteOfTheDay}</p>
    </div>
  );
}

We have the quoteOfTheDay string state and the quotes day created with the useState hook.

Then we add the getQuotes function which makes a GET request to an API to get a list of quotes.

We call res.json to return a promise with the quotes JSON.

Then we call setQuotes to set the quotes state.

The getRandomQuote function gets a random index with Math.random and Math.floor to round the decimal number down to the nearest integer.

Then we call setQuoteOfTheDay to set the quote to the string text property.

We have the useEffect callback to call getQuotes to get the quotes.

The 2nd argument is an empty array so it only runs when App mounts.

Then we return JSX with a button with the onClick prop set to getRandomQuote .

We run getRandomQuote when we click on the button.

And below that, we show the quoteOfTheDay .

Conclusion

We can create a quote of the day app easily with React and JavaScript.

Categories
React Projects

Create a Loan Calculator App with Vue 3 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 loan 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 loan-calculator

with NPM to create our React project.

Create the Loan Calculator App

To create the loan calculator app, we write:

import React, { useState } from "react";

export default function App() {
  const [loanAmount, setLoanAmount] = useState(0);
  const [interestRate, setInterestRate] = useState(0);
  const [numMonths, setNumMonth] = useState(0);
  const [monthlyPayment, setMonthlyPayment] = useState(0);

  const calculate = (e) => {
    e.preventDefault();
    const formValid =
      +loanAmount >= 0 &&
      0 <= +interestRate &&
      +interestRate <= 100 &&
      +numMonths > 0;
    if (!formValid) {
      return;
    }
    setMonthlyPayment((+loanAmount * (1 + +interestRate / 100)) / +numMonths);
  };

  return (
    <div className="App">
      <form onSubmit={calculate}>
        <div>
          <label>loan amount</label>
          <input
            value={loanAmount}
            onChange={(e) => setLoanAmount(e.target.value)}
          />
        </div>
        <div>
          <label>interest rate</label>
          <input
            value={interestRate}
            onChange={(e) => setInterestRate(e.target.value)}
          />
        </div>
        <div>
          <label>number of months to pay off loan</label>
          <input
            value={numMonths}
            onChange={(e) => setNumMonth(e.target.value)}
          />
        </div>
        <button type="submit">calculate monthly payment</button>
      </form>
      <p>monthly payment: {monthlyPayment.toFixed(2)}</p>
    </div>
  );
}

We have the loanAmount , interestedRate , and numMonths states which are bound to the inputs with value and onChange .

onChange of each input are set to a function that calls the respective state change functions to set the state.

e.target.value has the inputted value.

The monthlyPayment state has the monthly payment result.

Then we add the calculate function that calculates the monthlyPayment .

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

We check if each value is valid with the formValid expression.

If they are, then we call setMonthlyPayment to set the monthlyPayment value.

In the JSX, we have the form with the onSubmit prop set to the calculate function.

It’s called when we click on calculate monthly.

Below the form, we show the monthly payment.

Conclusion

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