Categories
React Projects

Create a Weather 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 weather 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 weather-app

with NPM to create our React project.

Create the Weather App

To create the weather app, we write:

import React, { useState } from "react";
const APIKEY = "your-key";

export default function App() {
  const [city, setCity] = useState("");
  const [result, setResult] = useState({});

  const getWeather = async (e) => {
    e.preventDefault();
    if (!city) {
      return;
    }
    const res = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKEY}`
    );
    const { main } = await res.json();
    setResult(main);
  };

  return (
    <div>
      <form onSubmit={getWeather}>
        <div>
          <label>city</label>
          <input value={city} onChange={(e) => setCity(e.target.value)} />
        </div>
        <button type="submit">get weather</button>
      </form>
      {result && (
        <div>
          <p>feels like: {result.feels_like}</p>
          <p>humidity: {result.humidity}</p>
          <p>pressure: {result.pressure}</p>
          <p>temperature: {result.temp}</p>
          <p>high: {result.temp_max}</p>
          <p>low: {result.temp_min}</p>
        </div>
      )}
    </div>
  );
}

We define the APIKEY variable set to the API key for the OpenWeather API.

The API key can be obtained for free from https://home.openweathermap.org/api_keys.

Next, we define the city state which we use to bind the inputted value of the city field to it.

The result field has the weather results.

Next, we define the getWeather function to get the weather data by city .

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

Then we check if city is set.

If it’s set, then we make an API request to the Open Weather API with fetch .

And we call setResult to set the result.

Below that, we create a form with the onSubmit prop set to getWeather so that getWeather is called when we click on the get weather button.

Inside the form, we have an input set to a value and onChange props.

onChange is set to a function to set the city state’s value.

e.target.value has the inputted value.

Below the form, we show the result properties top the user.

Conclusion

We can create a weather app easily with React and JavaScript.

Categories
React Projects

Create a Voting 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 voting 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 voting-app

with NPM to create our React project.

Create the Voting App

To create the voting app, we write:

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

export default function App() {
  const [choice, setChoice] = useState("");
  const [results, setResults] = useState({});

  const vote = () => {
    if (!localStorage.getItem("vote-result")) {
      localStorage.setItem("vote-result", JSON.stringify({}));
    }
    setResults({ ...results, [choice]: (results[choice] ?? 0) + 1 });
  };

  useEffect(() => {
    localStorage.setItem("vote-result", JSON.stringify(results));
  }, [results]);

  return (
    <div>
      <form>
        <div>
          <label>What's your favorite fruit?</label>
          <input
            type="radio"
            value="apple"
            checked={"apple" === choice}
            onChange={(e) => setChoice(e.target.value)}
          />
          apple
          <input
            type="radio"
            value="orange"
            checked={"orange" === choice}
            onChange={(e) => setChoice(e.target.value)}
          />
          orange
          <input
            type="radio"
            value="grape"
            checked={"grape" === choice}
            onChange={(e) => setChoice(e.target.value)}
          />
          grape
        </div>
        <button type="button" onClick={vote}>
          vote
        </button>
      </form>
      <div>
        <h1>result</h1>
        {Object.entries(results).map(([key, val]) => {
          return (
            <p key={key}>
              {key}: {val}
            </p>
          );
        })}
      </div>
    </div>
  );
}

We create the choice state that stores the choice that the user selects.

Then we define the results state that stores the vote results.

Next, we define the vote function that gets the local storage item with the key vote-result.

If it’s not set, then we add it.

Next, we set the results state with setResults .

We make a copy of results and then add the choices to it.

?? is the nullish coalescing operator, which returns 0 only if results[choice] isn’t set or is undefined .

Then we add 1 to it to register the vote.

Next, we call useEffect with a callback that calls localStorage.setItem to store the latest result value in local storage.

Below that, we define a form with the question and the choices to choose from.

We have the radio button inputs.

We set them to different values, and we set the checked value so that they’re checked when we make the choice.

And in the onChange callback, we call setChoice with e.target.value to set choice to the selected value.

We call vote when we click on the vote button.

Below the form, we show the results to the user.

Object.entries returns an array of keys and values of the object in an array.

The array entries are the arrays of keys and values.

Conclusion

We can create a voting app easily with React and JavaScript.

Categories
React Projects

Create a Drawing 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 drawing 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 drawing-app

with NPM to create our React project.

Create the Drawing App

To create the drawing app, we write:

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

export default function App() {
  const canvas = useRef();
  const [pos, setPos] = useState({});

  const setPosition = (e) => {
    setPos({
      x: e.clientX,
      y: e.clientY
    });
  };

  const resize = () => {
    const ctx = canvas.current.getContext("2d");
    ctx.canvas.width = window.innerWidth;
    ctx.canvas.height = window.innerHeight;
  };

  const draw = (e) => {
    if (e.buttons !== 1) {
      return;
    }
    const ctx = canvas.current.getContext("2d");
    ctx.beginPath();
    ctx.lineWidth = 5;
    ctx.lineCap = "round";
    ctx.strokeStyle = "green";
    ctx.moveTo(pos.x, pos.y);
    setPosition(e);
    ctx.lineTo(pos.x, pos.y);
    ctx.stroke();
  };

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

  return (
    <div>
      <style>
        {`
          #canvas {
            border: 1px solid black;
          }
        `}
      </style>
      <canvas
        ref={canvas}
        onMouseMove={draw}
        onMouseDown={setPosition}
        onMouseEnter={setPosition}
        id="canvas"
      ></canvas>
    </div>
  );
}

We create the canvas ref which will be assigned to the canvas element.

Then we define the pos state to set the position of the canvas pointer.

Then we define the setPosition function which sets the pos state value from the clientX and clientY event property values.

Next, we define the resize function that gets the canvas and then set the width and height of the canvas when the window is resized.

After that, we define the draw function to draw the line.

We get the e parameter with the event object.

First, we check if we click on the left button by checking if e.buttons is 1.

We continue only if e.buttons is 1.

Next, we get the canvas element object.

Then we call beginPath to start drawing.

And we set the line width, line cap style, and stroke style.

Then we call moveTo to move the pointer to the given position.

Then we call setPosition to set the pos value to the same value.

And we call lineTo again with the end coordinate of the line to set the end coordinate of the line.

And then we call ctx.stroke to draw the line.

Then we add the useEffect hook with a callback that resizes the canvas when we resize the window.

And below that, we add the style element to add a border to the canvas.

And finally, we add the canvas and assign the event handlers that are run when we click and move the mouse.

Conclusion

We can create a drawing app easily with React and JavaScript.

Categories
React Projects

Create a Currency 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 currency converter 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 currency-converter

with NPM to create our React project.

Create the Currency Converter

To create the currency converter, we write:

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

export default function App() {
  const [value, setValue] = useState(0);
  const [fromCurrency, setFromCurrency] = useState("");
  const [toCurrency, setToCurrency] = useState("");
  const [currencies] = useState(["EUR", "USD", "CAD"]);
  const [result, setResult] = useState(0);

  const fromCurrencies = useMemo(() => {
    return currencies.filter((c) => c !== toCurrency);
  }, [currencies, toCurrency]);

  const toCurrencies = useMemo(() => {
    return currencies.filter((c) => c !== fromCurrency);
  }, [currencies, fromCurrency]);

  const convert = async (e) => {
    e.preventDefault();
    const formValid = +value >= 0 && fromCurrency && toCurrency;
    if (!formValid) {
      return;
    }
    const res = await fetch(
      `https://api.exchangeratesapi.io/latest?base=${fromCurrency}`
    );
    const { rates } = await res.json();
    setResult(+value * rates[toCurrency]);
  };

  return (
    <div>
      <form onSubmit={convert}>
        <div>
          <label>value</label>
          <input value={value} onChange={(e) => setValue(e.target.value)} />
        </div>
        <div>
          <label>from currency</label>
          <select
            value={fromCurrency}
            onChange={(e) => setFromCurrency(e.target.value)}
          >
            {fromCurrencies.map((c) => (
              <option key={c}>{c}</option>
            ))}
          </select>
        </div>
        <div>
          <label>to currency</label>
          <select
            value={toCurrency}
            onChange={(e) => setToCurrency(e.target.value)}
          >
            {toCurrencies.map((c) => (
              <option key={c}>{c}</option>
            ))}
          </select>
        </div>
        <button type="submit">convert</button>
      </form>
      <div>
        {value} {fromCurrency} is {result.toFixed(2)} {toCurrency}
      </div>
    </div>
  );
}

We have the value state that stores the value of the currency value to convert from.

fromCurrency has the currency to convert from.

toCurrency has the currency to convert to,

currencies has the currency choices.

result has the converted result.

fromCurrencies has the choices we can choose to convert from.

We use the useMemo hook with a callback to return all the currencies that we can pick from.

We exclude the toCurrency value from the returned array.

The 2nd argument has the values to watch in order for the first callback to run again to update the returned value.

Likewise, we do the same to define toCurrencies but we exclude the fromCurrency value instead.

Next, we define the convert function that does the currency conversion.

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

Then we check if value is bigger than 0 and fromCurrency and toCurrency are set.

If all the conditions are met, we get the exchange rate from the Exchange Rate API.

Then we call setResult to compute converted currency value.

Next, we add the form to let us enter the values.

It has the onSubmit prop set to the convert function, which is run when we click on the button that has the type submit .

In it, it has an input to set the value .

e.target.value has the inputted value.

onChange is run whenever we change the entered value.

Likewise, we have the select dropdowns that lets us choose the currencies to convert from and to respectively.

We set their values as we did with the input with the value and onChange props.

We render the fromCurrencies and toCurrencies inside the select element to render the choices.

Below the form, we show the result to the user.

The toFixed method returns the string form of the number with the number of decimal places we pass in.

Conclusion

We can create a currency converter with React and JavaScript.

Categories
React Projects

Create a Recipe 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 recipe 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 recipe-app

with NPM to create our React project.

We also need the uuid package to let us generate unique IDs for our recipe items.

To do this, we run:

npm i uuid

Create the Recipe App

To create the recipe app, we write:

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

export default function App() {
  const [recipe, setRecipe] = useState({
    name: "",
    ingredients: "",
    steps: ""
  });
  const [recipes, setRecipes] = useState([]);

  const addRecipe = (e) => {
    e.preventDefault();
    const { name, ingredients, steps } = recipe;
    const formValid = name && ingredients && steps;
    if (!formValid) {
      return;
    }
    setRecipes((recipes) => [
      ...recipes,
      {
        id: uuidv4(),
        ...recipe
      }
    ]);
  };

  const deleteRecipe = (index) => {
    setRecipes((recipes) => recipes.filter((_, i) => i !== index));
  };

  return (
    <div>
      <style>
        {`
        .content {
          white-space: pre-wrap;
        }
        `}
      </style>
      <form onSubmit={addRecipe}>
        <div>
          <label>name</label>
          <input
            value={recipe.name}
            onChange={(e) =>
              setRecipe((recipe) => ({ ...recipe, name: e.target.value }))
            }
          />
        </div>
        <div>
          <label>ingredients</label>
          <input
            value={recipe.ingredients}
            onChange={(e) =>
              setRecipe((recipe) => ({
                ...recipe,
                ingredients: e.target.value
              }))
            }
          />
        </div>
        <div>
          <label>steps</label>
          <textarea
            value={recipe.steps}
            onChange={(e) =>
              setRecipe((recipe) => ({ ...recipe, steps: e.target.value }))
            }
          ></textarea>
        </div>
        <button type="submit">add recipe</button>
      </form>
      {recipes.map((r, index) => {
        return (
          <div key={r.id}>
            <h1>{r.name}</h1>
            <h2>ingredients</h2>
            <div className="content">{r.ingredients}</div>
            <h2>steps</h2>
            <div className="content">{r.steps}</div>
            <button className="button" onClick={() => deleteRecipe(index)}>
              delete
            </button>
          </div>
        );
      })}
    </div>
  );
}

We have the recipe state which is used to store the form data.

recipes has the recipe entries.

Then we define the addRecipe function that lets us add a recipe.

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

Then we check if name , ingredients , and steps are set.

If they are, then we call setRecipes to add the entry.

We pass in a callback that takes the existing recipes value, then we return a copy of it with an object that has the new entry at the end.

We call uuidv4 to return a unique ID for the new entry.

The deleteRecipe function calls setRecipes with a callback that takes the existing recipes . Then it returns a copy of it without the entry at the given index .

Below that, we add the style element to style the steps.

And we have the form with the onSubmit prop set to addRecipe to add an entry when we click on the button with type submit .

Inside the form, we have the inputs with an onChange prop that are set to functions that call setRecipe to set the inputted value to a property in the recipe object.

Below the form, we render the recipes values into a div.

Inside it, we show the name , ingredients , and steps .

And below that, we have a button that calls deleteRecipe with the index when we click it.

Conclusion

We can create a recipe app with React and JavaScript.