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.

Categories
React Projects

Create a Grade 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 grade 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 grade-calculator

with NPM to create our React project.

Also, we’ve to install the uuid package to let us assign unique IDs for each grade entry.

To do this, we run:

npm i uuid

Create the Grade Calculator

To create the grade calculator, we write:

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

export default function App() {
  const [grades, setGrades] = useState([{ id: uuidv4(), value: 0 }]);
  const [average, setAverage] = useState(0);

  const addGrade = () => {
    setGrades((grades) => [...grades, { id: uuidv4(), value: 0 }]);
  };

  const deleteGrade = (index) => {
    setGrades((grades) => grades.filter((_, i) => i !== index));
  };

  const calculate = (e) => {
    e.preventDefault();
    const formValid = grades.every(({ value }) => !isNaN(+value));
    if (!formValid) {
      return;
    }
    setAverage(
      grades.map(({ value }) => value).reduce((a, b) => +a + +b, 0) /
        grades.length
    );
  };

  return (
    <div className="App">
      <form onSubmit={calculate}>
        {grades.map((g, i) => {
          return (
            <div key={g.id}>
              <label>grade</label>
              <input
                value={g.value}
                onChange={(e) => {
                  const grds = [...grades];
                  grds[i].value = e.target.value;
                  setGrades(grds);
                }}
              />
              <button type="button" onClick={() => deleteGrade(i)}>
                delete grade
              </button>
            </div>
          );
        })}

        <button type="button" onClick={addGrade}>
          add grade
        </button>
        <button type="submit">calculate average</button>
      </form>
      <div>Your average grade is {average}</div>
    </div>
  );
}

We define the grades state set to an array with one entry initially.

Then we define the average state that holds the average grade.

The addGrade function lets us add a grade entry.

In it, we call setGrades with a callback that returns a copy of the grades array with a new entry at the end.

The id is set to the return value of uuidv4 to set the unique ID.

Then we create the deleteGrade function that calls setGrades with a callback that returns the grades array without the given index to remove the given entry from the grades array.

The calculate function calculates the average.

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

Then we check if each value property of each grade entry is a number.

If they are, then we call setAverage with an expression to calculate the average.

We map grades to an array with only the value values.

Then we call reduce on that array to add all the values together and return it with the callback.

The 2nd argument of reduce has the initial return value.

Below that, we have the form with the onSubmit prop set to submit to make the form submission.

Inside it, we render the grades array into an input.

The key prop is set to g.id to set it to a unique ID so that React can keep track of the entries.

The value is set to g.value .

In the onChange callback, we make a copy of grades . Then we set the value of the grades entry with the given index to e.target.value .

e.target.value has the inputted value.

Then we call setGrades to update the grades array with the latest values.

Below that, we have the delete grade button that calls deleteGrade when we click it.

And below the inputs, we have the add grade and calculate average buttons.

The add grade button calls addGrade when we click it.

And the calculate average button triggers the submit event since it has type submit .

And below the form, we show the average grade value.

Conclusion

We can create a grade calculator with Reacr and JavaScript.

Categories
React Projects

Create a Temperature 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 temperature 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 temperature-converter

with NPM to create our React project.

Create the Temperature Converter

To create the temperature converter, we write:

import React, { useState } from "react";

export default function App() {
  const [celsius, setCelsius] = useState(0);
  const [fahrenheit, setFahrenheit] = useState(0);

  const convert = (e) => {
    e.preventDefault();
    const formValid = !isNaN(+celsius);
    if (!formValid) {
      return;
    }
    setFahrenheit(+celsius * (9 / 5) + 32);
  };

  return (
    <div className="App">
      <form onSubmit={convert}>
        <div>
          <label>temperature in celsius</label>
          <input value={celsius} onChange={(e) => setCelsius(e.target.value)} />
        </div>
        <button type="submit">convert</button>
      </form>
      <div>
        {celsius}c is {fahrenheit}f
      </div>
    </div>
  );
}

We have the celsius and fahrenheit states which we use to set the celsius and Fahrenheit values respectively.

The convert function is where we convert the celsius value to fahrenheit .

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

Then we check is celsius is a number with isNaN .

If it’s a number, then we call setFahrenheit with the formula to compute the Fahrenheit from the celsius .

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

In it, we have an input to let us set the celsius .

value is set to celsius and the onChange prop is set to a function to set the celsius value.

e.target.value has the inputted value.

onSubmit is run when we click the button with type submit .

Below that, we display the celsius value and the fahrenheit equivalent.

Conclusion

We can create a temperature converter easily with React and JavaScript.

Categories
React Projects

Create a Palindrome Checker 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 palindrome checker 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 palindrome-checker

with NPM to create our React project.

Create the Palindrome Checker

To create the palindrome checker, we write:

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

export default function App() {
  const [word, setWord] = useState("");

  const isPalindrome = useMemo(() => {
    return word === word.split("").reverse().join("");
  }, [word]);

  return (
    <div className="App">
      <form>
        <div>
          <label>word to check</label>
          <input value={word} onChange={(e) => setWord(e.target.value)} />
        </div>
      </form>
      <div>Is Palindrome:{isPalindrome ? "Yes" : "No"}</div>
    </div>
  );
}

We have the word state which we bind to the input with the value and onChange props.

We set the value of it with the onChange prop, which has a function that calls setWord with e.target.value .

e.target.value has the inputted value.

Next, we create the isPalindrome variable with the useMemo hook.

The first argument of it is a callback that returns the comparison between word and the reversed word.

We reverse word with word.split to split the word into an array of characters.

Then we call reverse to reverse the character array.

And we call join to join the character array back to a string again.

In the 2nd argument, we pass in an array with the word entry so that the returned value in the callback in the 1st argument is updated whenever word changes.

In the form, we show the input and the value is isPalindrome to the user.

Conclusion

We can create a palindrome checker with React and JavaScript.

Categories
React Projects

Create an Audio Player 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 audio player 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 audio-player

with NPM to create our React project.

Create the Audio Player

To create the audio player, we write:

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

export default function App() {
  const audioPlayer = useRef();
  const [currentTime, setCurrentTime] = useState(0);
  const [seekValue, setSeekValue] = useState(0);

  const play = () => {
    audioPlayer.current.play();
  };

  const pause = () => {
    audioPlayer.current.pause();
  };

  const stop = () => {
    audioPlayer.current.pause();
    audioPlayer.current.currentTime = 0;
  };

  const setSpeed = (speed) => {
    audioPlayer.current.playbackRate = speed;
  };

  const onPlaying = () => {
    setCurrentTime(audioPlayer.current.currentTime);
    setSeekValue(
      (audioPlayer.current.currentTime / audioPlayer.current.duration) * 100
    );
  };

  return (
    <div className="App">
      <audio
        src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
        ref={audioPlayer}
        onTimeUpdate={onPlaying}
      >
        Your browser does not support the
        <code>audio</code> element.
      </audio>
      <br />
      <p>{currentTime}</p>
      <input
        type="range"
        min="0"
        max="100"
        step="1"
        value={seekValue}
        onChange={(e) => {
          const seekto = audioPlayer.current.duration * (+e.target.value / 100);
          audioPlayer.current.currentTime = seekto;
          setSeekValue(e.target.value);
        }}
      />
      <div>
        <button onClick={play}>play</button>
        <button onClick={pause}>pause</button>
        <button onClick={stop}>stop</button>
        <button onClick={() => setSpeed(0.5)}>0.5x</button>
        <button onClick={() => setSpeed(1)}>1x</button>
        <button onClick={() => setSpeed(1.5)}>1.5x</button>
        <button onClick={() => setSpeed(2)}>2x</button>
      </div>
    </div>
  );
}

We create the audioPlayer ref that we assign to the audio element.

Then we create the currentTime state to set the current time of the audio playback.

seekValue has the time value we seek to.

The play function gets the audioPlayer and call play on it to play the video.

The pause function calls pause on the audio element.

The stop function calls pause and also set the currentTime of the audio element to 0 to reset the play position back to the beginning.

The onPlaying function sets the currentTime to the audio element’s currentTime value in seconds.

setSeekValue sets the seekValue to a value between 0and 100.

Below that, we have the audio element that has the onTimeUpdate prop set to the onPlaying function to set the currentTime .

Then we show the currentTime to the user.

The range input lets us change its value by moving the slider dot.

value is set to seekValue which we can change and we change that with the onChange callback and the onPlaying function.

In the onChange prop, we also set the currentTime of the audio player element.

Below that, we have the play, pause, and stop buttons to call the respective functions when we click them.

And we have 3 buttons that call setSpeed when we click them.

Conclusion

We can create an audio player easily with React and JavaScript.