Categories
React Projects

Create a PIN Pad 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 PIN pad 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 pin-pad

with NPM to create our React project.

Create the PIN Pad

To create the PIN pad, we write:

import React, { useState } from "react";

export default function App() {
  const [pin, setPin] = useState("");

  return (
    <div>
      <div>{pin}</div>
      <div>
        <div>
          <button onClick={() => setPin((pin) => `${pin}1`)}>1</button>
          <button onClick={() => setPin((pin) => `${pin}2`)}>2</button>
          <button onClick={() => setPin((pin) => `${pin}3`)}>3</button>
        </div>
        <div>
          <button onClick={() => setPin((pin) => `${pin}4`)}>4</button>
          <button onClick={() => setPin((pin) => `${pin}5`)}>5</button>
          <button onClick={() => setPin((pin) => `${pin}6`)}>6</button>
        </div>
        <div>
          <button onClick={() => setPin((pin) => `${pin}7`)}>7</button>
          <button onClick={() => setPin((pin) => `${pin}8`)}>8</button>
          <button onClick={() => setPin((pin) => `${pin}9`)}>9</button>
        </div>
        <div>
          <button onClick={() => setPin((pin) => pin.slice(0, pin.length - 1))}>
            &lt;
          </button>
          <button onClick={() => setPin((pin) => `${pin}0`)}>0</button>
          <button onClick={() => setPin("")}>C</button>
        </div>
      </div>
    </div>
  );
}

We create the pin state to hold the string that’s created when we click the buttons.

Then we show the pin value.

And then we add the buttons which have the onClick prop set to a function that calls setPin with a callback that returns the pin string.

The < button has a setPin callback that returns the pin string with the last character removed.

And the C button has a setPin callback that resets pin to an empty string.

Conclusion

We can create a PIN pad easily with React and JavaScript.

Categories
React Projects

Create a Tic Tac Toe 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 a tic tac toe 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 tic-tac-toe

with NPM to create our React project.

Create the Tic Tac Toe Game

To create the tic tac toe game, we write:

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

export default function App() {
  const [board, setBoard] = useState([[], [], []]);

  const restart = () => {
    setBoard([[], [], []]);
  };

  const isWinner = (player) => {
    return (
      (board[0][0] === player &&
        board[0][1] === player &&
        board[0][2] === player) ||
      (board[1][0] === player &&
        board[1][1] === player &&
        board[1][2] === player) ||
      (board[2][0] === player &&
        board[2][1] === player &&
        board[2][2] === player) ||
      (board[0][0] === player &&
        board[1][0] === player &&
        board[2][0] === player) ||
      (board[0][1] === player &&
        board[1][1] === player &&
        board[2][1] === player) ||
      (board[0][2] === player &&
        board[1][2] === player &&
        board[2][2] === player) ||
      (board[0][0] === player &&
        board[1][1] === player &&
        board[2][2] === player) ||
      (board[0][2] === player &&
        board[1][1] === player &&
        board[2][0] === player)
    );
  };

  const xWins = useMemo(() => {
    return isWinner("x");
  }, [board, isWinner]);

  const oWins = useMemo(() => {
    return isWinner("o");
  }, [board, isWinner]);

  if (xWins || oWins) {
    if (xWins) {
      return (
        <>
          <div>x wins</div>
          <button onClick={restart}>restart</button>
        </>
      );
    }

    if (oWins) {
      return (
        <>
          <div>o wins</div>
          <button onClick={restart}>restart</button>
        </>
      );
    }
  } else {
    return (
      <div className="App">
        <form>
          {Array(3)
            .fill()
            .map((_, i) => {
              return (
                <div key={i}>
                  {Array(3)
                    .fill()
                    .map((_, j) => {
                      return (
                        <span key={j}>
                          <input
                            value={board[i][j] || ""}
                            onChange={(e) => {
                              const b = [...board];
                              b[i][j] = e.target.value;
                              setBoard(b);
                            }}
                            style={{ width: 20 }}
                          />
                        </span>
                      );
                    })}
                </div>
              );
            })}
        </form>
      </div>
    );
  }
}

We have the board state which holds the tic tac toe values.

The restart function calls setBoard to clear the board.

Then we have the isWinner function that checks if the player fills in the board in a way that the player wins.

We check each possible combination to see if the player wins, including horizontal, vertical, and diagonal combinations.

Then we define the xWins and oWins with useMemo with a callback that calls isWinner with the player string to see if the player wins.

We watch the board and isWinner variables for updates.

Then we check xWins and oWins .

In either case, we show who wins and the restart button.

Otherwise, we render the nested array into a grid of inputs.

Each input has the value set to the board[i][j] value.

Then to update the value when the user types it in, we have the onChange prop set to a function that makes a copy of the board and set it to b .

Then we set b[i][j] to e.target.value .

And then we call setBoard with b to update the board.

We set the input style to width 20px.

Conclusion

We can create a tic tac toe game with React and JavaScript.

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.