Categories
React Projects

Create a To-Do List 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 to-do list 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 todo-list

with NPM to create our React project.

We need the uuid to let us create unique IDs for our to-do items easily.

To add it, we run:

npm i uuidv4

Create the To-Do App

To create the to-do list app, we write:

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

export default function App() {
  const [todo, setTodo] = useState("");
  const [todos, setTodos] = useState([]);

  const submit = (e) => {
    e.preventDefault();
    setTodos((todos) => [
      ...todos,
      {
        id: uuidv4(),
        todo
      }
    ]);
  };

  const deleteTodo = (index) => {
    setTodos((todos) => todos.filter((_, i) => i !== index));
  };

  return (
    <div className="App">
      <form onSubmit={submit}>
        <input value={todo} onChange={(e) => setTodo(e.target.value)} />
        <button type="submit">Add</button>
      </form>
      {todos.map((t, i) => {
        return (
          <div key={t.id}>
            {t.todo}
            <button onClick={() => deleteTodo(i)}>delete</button>
          </div>
        );
      })}
    </div>
  );
}

We have the todo state which is bound to the input box.

The todos state has an array of to-do items.

The submit method is where we add the to-do items to the todos array.

We call e.preventDefault() to stop server-side form submission.

Then we call setTodos with a callback to get the todos and return an array with the original todos items.

After that, we append the new item to it.

It has an id created from the uuidv4 function.

todo has the to-do item text.

The deleteTodo function is called when we click the delete button.

In it, we call the setTodos method with a callback that takes the original todos array.

Then we return an array without the entry with the given index .

We filter that entry out with the filter method.

Then in the return statement, we have a form that has the input element with the value and onChange props to get the input value and set it with the onChange callback respectively.

onSubmit has the submit function as its value. submit is called when we click the Add button.

Below that, we have todos.map callback with a callback that returns a div with the t.todo rendered and a button to delete the item when we click it.

The key prop is set to t.id which is the unique ID.

This helps React identify the rendered array items properly.

Conclusion

We can create a to-do list app easily with React and JavaScript.

Categories
React Projects

Create a Simple 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 simple 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 simple-calculator

with NPM to create our React project.

Also, we’ve to install the mathjs library so that we can evaluate math expressions in strings easily.

To install it, we run:

npm i mathjs

Create the Calculator App

To create the calculator app, we write:

import { useState } from "react";
import { evaluate } from "mathjs";

export default function App() {
  const [expression, setExpression] = useState("");

  const submit = (e) => {
    e.preventDefault();
    setExpression((ex) => evaluate(ex));
  };

  return (
    <div className="App">
      <style>
        {`button {
          width: 20px
        }`}
      </style>
      <div>{expression}</div>
      <form onSubmit={submit}>
        <div>
          <button type="button" onClick={() => setExpression((ex) => `${ex}+`)}>
            +
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}-`)}>
            -
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}*`)}>
            *
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}/`)}>
            /
          </button>
        </div>
        <div>
          <button type="button" onClick={() => setExpression((ex) => `${ex}.`)}>
            .
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}9`)}>
            9
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}8`)}>
            8
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}7`)}>
            7
          </button>
        </div>
        <div>
          <button type="button" onClick={() => setExpression((ex) => `${ex}6`)}>
            6
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}5`)}>
            5
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}4`)}>
            4
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}3`)}>
            3
          </button>
        </div>
        <div>
          <button type="button" onClick={() => setExpression((ex) => `${ex}2`)}>
            2
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}1`)}>
            1
          </button>
          <button type="button" onClick={() => setExpression((ex) => `${ex}0`)}>
            0
          </button>
          <button type="submit">=</button>
        </div>
        <div>
          <button
            type="button"
            style={{ width: 50 }}
            onClick={() => setExpression("")}
          >
            Clear
          </button>
        </div>
      </form>
    </div>
  );
}

We have the expression state which we create with the useState hook.

It’s set to an empty string as its initial value.

Then we return the JSX code with the keypad and the expression display.

We also have a style tag to set button elements to 20px width.

Most buttons except the = button all call setExpression to append a character to expression .

The callback has the ex parameter which is the current value of expression .

We return the new value for expression .

The form element has the onSubmit prop set to the submit function.

In submit , we call e.preventDefault() to prevent server-side form submission.

Then we call setExpression with a callback to return the returned value from mathjs ‘s evaluate method, which returns the evaluated value of the expression string.

The Clear button sets expression back to an empty string when we click it.

Conclusion

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

Categories
React Projects

Create a Tip 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 tip 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 tip-calculator

with NPM to create our React project.

Create the Tip Calculator App

To create the tip calculator app, we write:

import { useState } from "react";

export default function App() {
  const [subtotal, setSubtotal] = useState(0);
  const [numDiners, setNumDiners] = useState(0);
  const [tipPercentage, setTipPercetnage] = useState(0);
  const [result, setResult] = useState({});

  const submit = (e) => {
    e.preventDefault();
    if (+subtotal <= 0 || +numDiners <= 0 || +tipPercentage <= 0) {
      return;
    }
    const total = +subtotal * (1 + +tipPercentage);
    setResult({ total, totalPerDiner: +total / +numDiners });
  };

  return (
    <div className="App">
      <form onSubmit={submit}>
        <fieldset>
          <label>subtotal</label>
          <input
            value={subtotal}
            onChange={(e) => setSubtotal(e.target.value)}
          />
        </fieldset>

        <fieldset>
          <label>number of people sharing the bill</label>
          <input
            value={numDiners}
            onChange={(e) => setNumDiners(e.target.value)}
          />
        </fieldset>

        <fieldset>
          <label>tip percentage</label>
          <select
            value={tipPercentage}
            onChange={(e) => setTipPercetnage(e.target.value)}
          >
            <option value="0">0%</option>
            <option value="0.05">5%</option>
            <option value="0.1">10%</option>
            <option value="0.15">15%</option>
            <option value="0.2">20%</option>
          </select>
        </fieldset>

        <button type="submit">Calculate</button>
      </form>
      <p>total: {result.total && result.total.toFixed(2)}</p>
      <p>
        total per diner:{" "}
        {result.totalPerDiner && result.totalPerDiner.toFixed(2)}
      </p>
    </div>
  );
}

We have the subtotal , numDiners , tipPercentage , and result states.

subtotal is the subtotal.

numDiners is the number of diners.

tipPercentage has the tip percentage between 0 and 100.

In the submit function, we call e.preventDefault() to prevent server-side form submission.

Then we check if the values are valid with the if block.

Then we compute the total and the result object and call setResult to set it.

In the return statement, we have the input fields with the value and onChange properties to get and set the values respectively.

We get the value from e.target.value .

The form has the onSubmit prop to set the submit event listener.

Below that, we have the result data displayed.

Conclusion

We can create a tip calculator with React and JavaScript.

Categories
React Projects

Create an Image Modal 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 image modal 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 image-modal

with NPM to create our React project.

Create the Image Modal App

To create the image modal app, we write:

import { useState, useEffect } from "react";

const images = [
  "https://images.dog.ceo/breeds/pomeranian/n02112018_5091.jpg",
  "https://images.dog.ceo/breeds/mountain-swiss/n02107574_753.jpg",
  "https://images.dog.ceo/breeds/leonberg/n02111129_3028.jpg"
];

export default function App() {
  const [index, setIndex] = useState(0);
  const [displayModal, setDisplayModal] = useState(false);
  const next = () => {
    setIndex((i) => (i + 1) % images.length);
  };
  const prev = () => {
    setIndex(
      (i) => (((i - 1) % images.length) + images.length) % images.length
    );
  };
  const onClickOutside = (e) => {
    if (e.target.localName !== "button") {
      setDisplayModal(false);
    }
  };

  useEffect(() => {
    window.addEventListener("click", onClickOutside);
    return () => window.removeEventListener("click", onClickOutside);
  }, []);

  return (
    <div className="App">
      <button onClick={() => setDisplayModal(true)}>open modal</button>
      {displayModal && (
        <div
          style={{
            position: "absolute",
            top: 20,
            left: 20,
            border: "1px solid gray",
            backgroundColor: "white"
          }}
        >
          <button onClick={prev}>&lt;</button>
          <img src={images[index]} alt="" style={{ width: 200, height: 200 }} />
          <button onClick={next}>&gt;</button>
        </div>
      )}
    </div>
  );
}

We have the images array with URLs of images.

The index state is created with the useState hook to let us get an images entry by its index.

The displayModal state lets us control whether to display the modal or not.

The next and prev methods cycles through the images indexes to rotate the images.

We pass in a callback to the setIndex function to return the latest value based on the current value of index , which is stored in the i parameter.

onClickOutside checks if we clicked on a button.

If we didn’t, then we call setDisplayModal to false to close the modal.

The useEffect callback adds the onClickOutside to listen to the click event of the window .

It returns a callback to let us remove the click listener with removeEventListener when we unmount it.

The empty array in the 2nd argument lets us run the useEffect callback only when we mount the App component.

In the return statement, we have a button that sets the displayModal to true when we click it.

Below that, we have the modal which is displayed with displayModal is true .

We set the modal div’s position property to absolute so that we can display it above other content.

top and left sets the position.

border adds a border.

And backgroundColor sets the background color.

Inside it, we have buttons that call prev and next when we click on them to cycle through the images.

And the img element displays the image.

Conclusion

We can add an image modal with React and JavaScript.

Categories
React Projects

Create a Search Filter 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 search filter 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 search-filter

with NPM to create our React project.

Create the Search Filter App

To create the search filter app, we write:

import { useState, useMemo } from "react";

const images = [
  {
    url: "https://images.dog.ceo/breeds/affenpinscher/n02110627_4597.jpg",
    description: "affenpinscher"
  },
  {
    url: "https://images.dog.ceo/breeds/akita/Akita_Inu_dog.jpg",
    description: "akita"
  },
  {
    url: "https://images.dog.ceo/breeds/retriever-golden/n02099601_7771.jpg",
    description: "golden retriever"
  }
];

export default function App() {
  const [keyword, setKeyword] = useState();
  const filteredImages = useMemo(() => {
    if (!keyword) {
      return images;
    }
    return images.filter(({ description }) => description.includes(keyword));
  }, [keyword]);

  return (
    <div className="App">
      <input value={keyword} onChange={(e) => setKeyword(e.target.value)} />
      <br />
      {filteredImages.map((fi) => {
        return (
          <div key={fi.description}>
            <img
              src={fi.url}
              alt={fi.description}
              style={{ width: 200, height: 200 }}
            />
            <p>{fi.description}</p>
          </div>
        );
      })}
    </div>
  );
}

We have the images array, which we want to search with the input box.

In the App component, we add the keyword state, which we create by th useState hook.

Then we use the useMemo hook to compute the filteredImages value.

We add a callback that checks for the keyword value.

If there’s no keyword value, then we return the images array.

Otherwise, we return the images array items that have the description that includes the keyword .

The 2nd argument has an array with the keyword variable since we want to updated filteredImages according to the keyword value.

filtereddImages is only updated with keyword changes.

Then in the return statement, we add the input box.

We set the onChange handler to set the keyword state.

Then we render the filteredImage items with the map method.

Conclusion

We can add a search filter easily with React’s useMemo hook and JavaScript.