Categories
React Projects

Create a Weight Converter App with React and JavaScript

Spread the love

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 weight converter 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 weight-converter

with NPM to create our React project.

Create the Weight Converter App

To create the weight converter app, we write:

import React, { useState } from "react";

export default function App() {
  const [weightInLb, setWeightInLb] = useState(0);
  const [weightInKg, setWeightInKg] = useState(0);

  const calculate = (e) => {
    e.preventDefault();
    const formValid = +weightInLb >= 0;
    if (!formValid) {
      return;
    }
    setWeightInKg(+weightInLb * 0.453592);
  };

  return (
    <div className="App">
      <form onSubmit={calculate}>
        <div>
          <label>weight in pounds</label>
          <input
            value={weightInLb}
            onChange={(e) => setWeightInLb(e.target.value)}
          />
        </div>
        <button type="submit">calculate</button>
      </form>
      <p>{weightInKg} kg</p>
    </div>
  );
}

We defined the weightInLb and weightInKg states with the useState hook.

Then we defined the calculate function to calculate the weightInKg value.

We call e.preventDefault() to do client-side form submission.

Then we check if weightInLb is bigger than or equal to 0.

If it is, then we calculate the weightInKg value, which is the weightInLb value converter to kilograms.

In the return statement, we have a form that has the onSubmit prop which runs the calculate function when the submit event is triggered.

The submit event is triggered by clicking the calculate button.

The input in the form has the value prop to set the value of the input.

The onChange has a function that takes the inputted value and calls setWeightInLb to set the weightInLb value.

e.target.value has the inputted value.

Below the form, we show the weightInKg value.

Conclusion

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

Leave a Reply

Your email address will not be published. Required fields are marked *