Categories
React Projects

Create a Pomodoro Timer 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 Pomodoro 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 pomodoro-timer

with NPM to create our React project.

Create the Pomodoro Timer App

To create the Pomodoro timer app, we write:

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

export default function App() {
  const [secondsLeft, setSecondsLeft] = useState(25 * 60);
  const [timer, setTimer] = useState();

  const start = () => {
    const timer = setInterval(() => {
      setSecondsLeft((secondsLeft) => secondsLeft - 1);
      if (secondsLeft === 0) {
        clearInterval(timer);
      }
    }, 1000);
    setTimer(timer);
  };

  useEffect(() => {
    if (secondsLeft === 0) {
      clearInterval(timer);
    }
  }, [secondsLeft, timer]);

  useEffect(() => {
    return () => clearInterval(timer);
  }, [timer]);

  return (
    <div className="App">
      <h1>Pomodoro Timer</h1>
      <button onClick={start}>start</button>
      <div>{secondsLeft} seconds left</div>
    </div>
  );
}

We define the secondsLeft state set to 25 * 60 seconds as the initial value.

Also, we define the timer state set to undefined as the initial value.

The start function creates a timer with the setInterval function.

The callback sets the secondsLeft state by decrementing it by 1.

If secondsLeft is 0, then we call clearInterval to clear the timer.

We run the setIntrval callback every second.

Also, we have the useEffect callback that returns a function to call clearInterval to clear the timer when we unmount the component.

Below that, we have a button to start the timer when we click on it.

And below that, we show the secondsLeft to the user.

Conclusion

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

Categories
React Projects

Create a Password Generator 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 password generator 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 password-generator

with NPM to create our React project.

Create the Password Generator App

To create the password generator app, we write:

import React, { useState } from "react";
const string = "abcdefghijklmnopqrstuvwxyz";
const numeric = "0123456789";
const punctuation = "!@#$%^&*()_+~`|}{[]:;?><,./-=";

export default function App() {
  const [length, setLength] = useState(10);
  const [password, setPassword] = useState("");

  const generatePassword = (e) => {
    e.preventDefault();
    const formValid = +length > 0;
    if (!formValid) {
      return;
    }
    let character = "";
    let password = "";
    while (password.length < length) {
      const entity1 = Math.ceil(string.length * Math.random() * Math.random());
      const entity2 = Math.ceil(numeric.length * Math.random() * Math.random());
      const entity3 = Math.ceil(
        punctuation.length * Math.random() * Math.random()
      );
      let hold = string.charAt(entity1);
      hold = password.length % 2 === 0 ? hold.toUpperCase() : hold;
      character += hold;
      character += numeric.charAt(entity2);
      character += punctuation.charAt(entity3);
      password = character;
    }
    password = password
      .split("")
      .sort(() => {
        return 0.5 - Math.random();
      })
      .join("");
    setPassword(password.substr(0, length));
  };

  return (
    <div className="App">
      <form onSubmit={generatePassword}>
        <div>
          <label>length</label>
          <input value={length} onChange={(e) => setLength(e.target.value)} />
        </div>
        <button type="submit">generate password</button>
      </form>
      <div>{password}</div>
    </div>
  );
}

We define the length state to hold the length.

password has the generated password.

Next, we define the generatePassword function to generate the password.

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

Then we check the length to see if it’s bigger than 0.

If it is, then we create the password.

To create it, we create 3 numbers and store them in entity1 , entity2 , and entity3 respectively.

Then we use them to get a value from string , numeric , and punctuation .

And then we append them to the character variable.

Then we assign the character value to password .

And then we shuffle the password characters with split , sort , and join .

The sort callback returns a random number between -0.5 and 0.5 to shuffle the numbers.

And finally, we call setPassword to set the password value.

Below that, we add a form with the onSubmit prop set to generatePassword to generate the password when we click the button with type submit .

The input hs the value and onChange props to get and set the length state respectively.

e.target.value has the input value.

Conclusion

We can create a password generator with React and JavaScript.

Categories
React Projects

Create an Address Book 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 address book 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 address-book

with NPM to create our React project.

Also, we’ve to install the uuid package to let us assign unique IDs to the contact entries.

To do this, we run:

npm i uuid

Create the Address Book App

To create the address book app, we write:

import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";

export default function App() {
  const [contact, setContact] = useState({
    name: "",
    address: "",
    phone: ""
  });
  const [contacts, setContacts] = useState([]);

  const addContact = (e) => {
    e.preventDefault();
    const { name, address, phone } = contact;
    const formValid =
      name &&
      address &&
      /^[(]{0,1}[0-9]{3}[)]{0,1}[-s.]{0,1}[0-9]{3}[-s.]{0,1}[0-9]{4}$/.test(
        phone
      );
    if (!formValid) {
      return;
    }
    setContacts((contacts) => [
      ...contacts,
      { id: uuidv4(), name, address, phone }
    ]);
  };

  const deleteContact = (index) => {
    setContacts((contacts) => contacts.filter((_, i) => i !== index));
  };

  return (
    <div className="App">
      <form onSubmit={addContact}>
        <div>
          <label>name</label>
          <input
            value={contact.name}
            onChange={(e) =>
              setContact((contact) => ({ ...contact, name: e.target.value }))
            }
          />
        </div>
        <div>
          <label>address</label>
          <input
            value={contact.address}
            onChange={(e) =>
              setContact((contact) => ({ ...contact, address: e.target.value }))
            }
          />
        </div>
        <div>
          <label>phone</label>
          <input
            value={contact.phone}
            onChange={(e) =>
              setContact((contact) => ({ ...contact, phone: e.target.value }))
            }
          />
        </div>
        <button type="submit">add</button>
      </form>
      {contacts.map((contact, index) => {
        return (
          <div key={contact.id}>
            <p>name : {contact.name}</p>
            <p>address : {contact.address}</p>
            <p>phone : {contact.phone}</p>
            <button type="button" onClick={() => deleteContact(index)}>
              delete
            </button>
          </div>
        );
      })}
    </div>
  );
}

We define the contact state that’s used to store the form’s data.

And the contacts state is defined to store the contacts entries.

Next, we define the addContact function.

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

Then we check if name , address and phone values are valid.

If they are, then we call setContacts with a callback that returns a copy of the contacts array with a new entry at the end to add the entry.

uuidv4 returns the unique ID for the contact.

The deleteContact removes an entry by calling setContacts with a callback that returns a copy of the contacts array without the item at the given index .

Below that, we add a form with the onSubmit prop set to addContact so addContact can be run when we click on the button with type submit .

Inside the form, we define 3 inputs with the value prop to get the value from the state.

And their onChange props are set to functions that call setContact with a callback that returns a copy of the contact value but with the new value for the property that it sets.

e.target.value has the inputted value.

Below the form, we render the contacts state by calling map with a callback that returns a div with the property values of each contact entry displayed.

The key prop is set to contact.id so that React can distinguish between the entries.

And below that, we show the delete that calls deleteContact with index when we click it.

Conclusion

We can create an address book app easily with React and JavaScript.

Categories
React Projects

Create an Issue Tracker 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 issue tracker 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 issue-tracker

with NPM to create our React project.

Also, we’ve to install the uuid package to let us assign unique IDs to the issue entries.

To do this, we run:

npm i uuid

Create the Issue Tracker

To create the issue tracker, we write:

import React, { useState } from "react";
import { v4 as uuidv4 } from "uuid";

export default function App() {
  const [issue, setIssue] = useState({
    description: "",
    priority: "low",
    assignee: ""
  });
  const [issues, setIssues] = useState([]);

  const addIssue = (e) => {
    e.preventDefault();
    const { description, priority, assignee } = issue;
    const formValid = description && priority && assignee;
    if (!formValid) {
      return;
    }
    setIssues((issues) => [
      ...issues,
      { id: uuidv4(), description, priority, assignee }
    ]);
  };

  const deleteIssue = (index) => {
    setIssues((issues) => issues.filter((_, i) => i !== index));
  };

  return (
    <div className="App">
      <form onSubmit={addIssue}>
        <div>
          <label>description</label>
          <input
            value={issue.description}
            onChange={(e) =>
              setIssue((issue) => ({ ...issue, description: e.target.value }))
            }
          />
        </div>

        <div>
          <label>priority</label>
          <select
            value={issue.priority}
            onChange={(e) =>
              setIssue((issue) => ({ ...issue, priority: e.target.value }))
            }
          >
            <option>low</option>
            <option>medium</option>
            <option>high</option>
          </select>
        </div>

        <div>
          <label>assignee</label>
          <input
            value={issue.assignee}
            onChange={(e) =>
              setIssue((issue) => ({ ...issue, assignee: e.target.value }))
            }
          />
        </div>
        <button type="submit">add issue</button>
      </form>
      {issues.map((issue, index) => {
        return (
          <div key={issue.id}>
            <p>description: {issue.description}</p>
            <p>priority: {issue.priority}</p>
            <p>assignee: {issue.assignee}</p>
            <button type="button" onClick={() => deleteIssue(index)}>
              delete issue
            </button>
          </div>
        );
      })}
    </div>
  );
}

We define the issue state which is an object.

Then we define the issues state which is an array.

Next, we define the addIssue function to add items to issues .

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

Then we check if description , priority and assignee have values.

If they have, then we call setIssues with a callback that returns a copy of the issues array with a new entry added to it.

The uuidv4 function returns a unique ID for the issues entry.

Next, we define the deleteIssue function which calls setIssues with a callback that returns a copy of the issues array without the entry with the given index .

Below that, we add a form with the onSubmit prop set to addIssue to let us add an entry to the issues array.

Inside it, we have 2 inputs and one select element with their value and onChange props set.

value has the value of each field.

And the onChange prop let us set the values.

We set them to functions that call setIssue with a callback that returns a copy of the issue object with a new property overwriting the existing one.

Then button with type submit runs the onSubmit handler when we click it.

Below that, we call issues.map to render divs with the issue values.

And below that, we add a button with the onClick prop set to a function that calls deleteIssue to remove the issue with the given index .

Conclusion

We can create an issue tracker with React and JavaScript.

Categories
React Projects

Create a Percentage Calculator 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 percentage calculator 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 percentage-calculator

with NPM to create our React project.

Create the Percentage Calculator

To create the percentage calculator, we write:

import React, { useState } from "react";

export default function App() {
  const [pointsGiven, setPointsGiven] = useState(0);
  const [pointsPossible, setPointsPossible] = useState(0);
  const [percentage, setPercentage] = useState(0);

  const calculate = (e) => {
    e.preventDefault();
    const formValid = +pointsGiven >= 0 && +pointsPossible > 0;
    if (!formValid) {
      return;
    }
    setPercentage((+pointsGiven / +pointsPossible) * 100);
  };

  return (
    <div className="App">
      <form onSubmit={calculate}>
        <div>
          <label>points given</label>
          <input
            value={pointsGiven}
            onChange={(e) => setPointsGiven(e.target.value)}
          />
        </div>

        <div>
          <label>points possible</label>
          <input
            value={pointsPossible}
            onChange={(e) => setPointsPossible(e.target.value)}
          />
        </div>
        <button type="submit">calculate</button>
      </form>
      <div>percentage:{percentage}</div>
    </div>
  );
}

We have the pointsGiven , pointsPossible , and the percentage states which are all numbers.

Next, we define the calculate function to calculate the percentage from pointsGiven and pointsPossible .

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

Next, we check if pointsGiven and pointsPossible are 0 or larger.

If they are, then we call setPercentage with the expression to calculate the percentage .

Next, we add the form with the onSubmit prop to add the submit handler.

In it, we have the inputs with the value and onChange prop to get and set the states respectively.

e.target.value has the inputted value so we can use it to set the states.

The submit handler is run when we click on the button with type submit .

Below the form, we show the percentage result.

Conclusion

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