Categories
React Answers React Projects

How to Create a Countdown Timer with React?

Sometimes, we want to create a countdown timer with React.

In this article, we’ll look at how to create a countdown timer with React.

Create a Countdown Timer with React

We can create a countdown timer by creating a timer component that updates the remaining time regularly.

To do this, we write:

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

const Timer = (props) => {
  const { initialMinute = 0, initialSeconds = 0 } = props;
  const [minutes, setMinutes] = useState(initialMinute);
  const [seconds, setSeconds] = useState(initialSeconds);
  useEffect(() => {
    const myInterval = setInterval(() => {
      if (seconds > 0) {
        setSeconds(seconds - 1);
      }
      if (seconds === 0) {
        if (minutes === 0) {
          clearInterval(myInterval);
        } else {
          setMinutes(minutes - 1);
          setSeconds(59);
        }
      }
    }, 1000);
    return () => {
      clearInterval(myInterval);
    };
  });

  return (
    <div>
      {minutes === 0 && seconds === 0 ? null : (
        <h1>
          {minutes}:{seconds < 10 ? `0${seconds}` : seconds}
        </h1>
      )}
    </div>
  );
};

export default function App() {
  return (
    <>
      <Timer initialMinute={5} initialSeconds={0} />
    </>
  );
}

We create the Timer component that takes the initialMinute and initialSeconds props that sets the initial time.

Then we use the useState prop to create the minutes and seconds state.

Next, we call the useEffect hook with a callback that creates a timer with setInterval .

The timer runs every second.

The setInterval callback checks if the seconds is bigger than 0 and calls setSeconds to decrease the seconds.

If seconds is 0 and minutes is 0, then we call clearInteraval to stop the timer.

Otherwise, we call setMinutes to minutes — 1 and call setSeconds to 59 decrements the minute.

Then we return a callback that calls clearInterval to clear the timer.

Below that, we render the minutes and seconds onto the screen.

If seconds is less than 10 then we add a 0 in front of it.

Conclusion

We can create a countdown timer by creating a timer component that updates the remaining time regularly.

Categories
React Projects

Create an RSS Reader 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 RSS reader 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 rss-reader

with NPM to create our React project.

Create the RSS Reader

To create the RSS reader, we write:

import React, { useState } from "react";

export default function App() {
  const [rssUrl, setRssUrl] = useState("");
  const [items, setItems] = useState([]);

  const getRss = async (e) => {
    e.preventDefault();
    const urlRegex = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/;
    if (!urlRegex.test(rssUrl)) {
      return;
    }
    const res = await fetch(`https://api.allorigins.win/get?url=${rssUrl}`);
    const { contents } = await res.json();
    const feed = new window.DOMParser().parseFromString(contents, "text/xml");
    const items = feed.querySelectorAll("item");
    const feedItems = [...items].map((el) => ({
      link: el.querySelector("link").innerHTML,
      title: el.querySelector("title").innerHTML,
      author: el.querySelector("author").innerHTML
    }));
    setItems(feedItems);
  };

  return (
    <div className="App">
      <form onSubmit={getRss}>
        <div>
          <label> rss url</label>
          <br />
          <input onChange={(e) => setRssUrl(e.target.value)} value={rssUrl} />
        </div>
        <input type="submit" />
      </form>
      {items.map((item) => {
        return (
          <div>
            <h1>{item.title}</h1>
            <p>{item.author}</p>
            <a href={item.link}>{item.link}</a>
          </div>
        );
      })}
    </div>
  );
}

We have the rssUrl state that stores the RSS feed URL we enter.

And the items state store the feed items which we’ll get.

Then we define the getRSS function to get the RSS feed items when we click submit.

Next, we call e.preventDefault() to let us do client side submission.

Then we check if the rssUrl value is a valid URL string.

If it is, then we make a GET request with fetch to the RSS feed via a CORS proxy.

We use the allOrigins API to let us make cross-domain requests to the given feed.

We need this since cross-domain communication from the browser isn’t allows with most feeds.

We get the contents property from the object.

Then we parse the XML string with the DOMParser instance’s parseFromString method.

The first argument is the XML string.

And the 2nd argument is the content-type string.

feed is the XML DOM object with the whole XML tree.

Then we use querySelectorAll to get all the item nodes.

And then we use the spread operator to spread the items Node list to an array.

Then we can call map on it to select nodes inside the item nodes with querySelector and return an object with the innerHTML values.

We call setItems to set the items state.

Below that, we have the form with the onSubmit prop set to getRSS to let us run the function when we click on the input with type submit .

Inside the form, we have an input with the onChange prop set to a function that calls setRssUrl to set the inputted value as the value of the rssUrl state.

e.target.value has the inputted value.

value is set to rssUrl so that we can see the inputted value.

Below the form, we render the items into divs with the map method.

Conclusion

We can create an RSS reader easily with React and JavaScript.

Categories
React Projects

Create a Stopwatch 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 stopwatch 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 stopwatch

with NPM to create our React project.

Also, we have to install the moment library to make calculating and formatting the duration easier.

To install it, we run:

npm i moment

Create the Stopwatch App

To create the stopwatch, we write:

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

export default function App() {
  const [startDate, setStartDate] = useState(new Date());
  const [diff, setDiff] = useState("00:00:00");
  const [timer, setTimer] = useState();

  return (
    <div className="App">
      <button
        onClick={() => {
          setStartDate(new Date());
          const timer = setInterval(() => {
            let start = moment(startDate);
            let end = moment(new Date());
            let diff = end.diff(start);
            let f = moment.utc(diff).format("HH:mm:ss.SSS");
            setDiff(f);
          }, 1000);
          setTimer(timer);
        }}
      >
        start
      </button>
      <button onClick={() => clearInterval(timer)}>stop</button>
      <p>{diff}</p>
    </div>
  );
}

We have the startDate state to store the start date time.

diff stores the elapsed time as a string.

timer has the timer object.

Then we add a button with a function that calls setStartDate to set the start date.

Then we create a timer that runs every second with setInterval .

In the setInterval callback, we create moment objects from the startDate and the current date-time.

We call moment to create those objects.

Then we get the elapsed time between them with the diff method.

And then we get the elapsed time formatted into a string with the moment.utc method and the format method.

Also, we call setTimer to set the timer state to our setIntervaltimer.

Next, we have the stop button to call clearInterval to stop the timer.

And the p element displays the formatted elapsed time string.

Conclusion

We can create a stopwatch easily with React and JavaScript.

Categories
React Projects

Create a Drag and Drop 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 drag and drop 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 drag-and-drop

with NPM to create our React project.

Create the Drag and Drop App

To create the drag and drop app, we write:

import React, { useState } from "react";

export default function App() {
  const [origin, setOrigin] = useState(["apple", "orange", "grape"]);
  const [target, setTarget] = useState([]);

  const drag = (ev, text) => {
    ev.dataTransfer.setData("text", text);
  };

  const drop = (ev) => {
    const text = ev.dataTransfer.getData("text");
    const index = origin.findIndex((o) => o === text);
    setOrigin((origin) => origin.filter((_, i) => i !== index));
    setTarget((target) => [...target, text]);
  };

  return (
    <div>
      <style>
        {`
          .draggable {
            border: 1px solid black;
            margin-right: 5px;
          }

          #target {
            border: 1px solid black;
            width: 95vw;
            height: 100px;
            padding: 5px;
          }
          `}
      </style>
      <h2>Draggable Elements</h2>
      {origin.map((o) => {
        return (
          <div
            className="draggable"
            draggable
            onDragStart={(e) => drag(e, o)}
            key={o}
            onClick={(e) => e.stopPropagation()}
          >
            {o}
          </div>
        );
      })}

      <h2>Target</h2>
      <div id="target" onDragOver={(e) => e.preventDefault()} onDrop={drop}>
        {target.map((t) => {
          return (
            <div className="draggable" key={t}>
              {t}
            </div>
          );
        })}
      </div>
    </div>
  );
}

We have the origin array state that’s rendered into items that we can drag and drop.

The target array has the dropped items.

Next, we have the drag function that calls ev.dataTransfer.setData to set the data that we want to drag.

The first argument is the key that we can use to get the data.

And the 2nd argument is the data for the corresponding key.

Next, we have the drop method that calls ev.dataTransfer.getData with the key to get the data.

Then we call origin.findIndex to find the index for the data.

Next, we remove the item from the origin with setOrigin called with a callback that returns a copy of the origin array without the index .

And we call setTarget with a callback that returns a copy of the target array with the text value appended to it.

Below that, we have some styles for the drag and drop items and containers.

And below that, we render the origin items.

To make them draggable, we add the draggable prop.

Then we add the onDragStart prop and set a function that calls drag .

onClick is set to a function that calls e.stopPropagation to stop the click event from bubbling to parent and ancestor items.

And below that, we render the target items with the onDragOver and onDrop props.

onDragOver is set to a function that e.preventDefault() so we can do the dropping.

And onDrop is set to drop to let us move data from origin to target .

Conclusion

We can create a drag and drop app easily with React and JavaScript.

Categories
React Projects

Create a JSON to CSV Converter 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 JSON to CSV 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 json-to-csv

with NPM to create our React project.

Create the JSON to CSV Converter App

To create the JSON to CSV converter app, we write:

import React, { useState } from "react";

export default function App() {
  const [json, setJson] = useState("");
  const [csv, setCsv] = useState("");

  const convert = async (e) => {
    e.preventDefault();
    const parsedJson = JSON.parse(json);
    if (
      !Array.isArray(parsedJson) ||
      !parsedJson.every((p) => typeof p === "object" && p !== null)
    ) {
      return;
    }
    const heading = Object.keys(parsedJson[0]).join(",");
    const body = parsedJson.map((j) => Object.values(j).join(",")).join("n");
    setCsv(`${heading}${body}`);
  };

  return (
    <div>
      <form onSubmit={convert}>
        <div>
          <label>json</label>
          <textarea
            value={json}
            onChange={(e) => setJson(e.target.value)}
          ></textarea>
        </div>
        <button type="submit">convert</button>
      </form>
      <div>
        <label>csv</label>
        <textarea value={csv}></textarea>
      </div>
    </div>
  );
}

We define the json and csv states to hold the JSON and CSV strings respectively.

Then we define the convert function to convert the json to csv .

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

Then we parse the json string.

If the JSON isn’t a JSON array or if there are any items that aren’t objects, then we stop running the function.

Otherwise, we proceed to converting the JSON to CSV.

We use the property names as headings.

And we get them with the Object.keys method.

Then we call parsedJson.map to map the values to strings by joining the values with commas and then join them together with a new line character.

Then we call setCsv with the heading and body combined.

Below that, we have a form with the onSubmit prop set to convert .

convert is run when we click the convert button since its type is set to submit .

The text area in the form is bound to the json state with the value and onChange props.

The onChange prop is set to a function that calls setJson with e.target.value .

Below the form, we show a text area that holds the csv .

We display that by setting the value prop to it.

Conclusion

We can create a JSON to CSV converter with React and JavaScript.