Categories
React Projects

Create a Height 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 height 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 height-converter

with NPM to create our React project.

Create the Height Converter App

To create the height converter app, we write:

import React, { useState } from "react";

export default function App() {
  const [feet, setFeet] = useState(0);
  const [inches, setInches] = useState(0);
  const [centimeters, setCentimeters] = useState(0);

  const submit = (e) => {
    e.preventDefault();
    const formValid = +feet >= 0 && +inches >= 0;
    if (!formValid) {
      return;
    }
    setCentimeters((+feet + +inches / 12) * 12 * 2.54);
  };

  return (
    <div>
      <form onSubmit={submit}>
        <div>
          <label>feet</label>
          <input value={feet} onChange={(e) => setFeet(e.target.value)} />
        </div>
        <div>
          <label>inches</label>
          <input value={inches} onChange={(e) => setInches(e.target.value)} />
        </div>
        <button type="submit">calculate</button>
      </form>
      <p>{centimeters} cm</p>
    </div>
  );
}

We create the feet , inches and centimeters states with the useState hook.

Then we define the submit function to calculate the centimeters from feet and inches .

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

Then we check if feet and inches are valid numbers.

If they are, then we calculate the centimeters equivalent of the feet and inches and call setCentimeters to set the centimeter value.

Below that, we have the form.

We pass the submit function to the onSubmit hook to trigger submission when we click the calculate button.

The inputs are used to set feet and inches .

onChange is set to a function to set each value.

e.target.value has the inputted value.

Below that, we display the centimeters value.

Conclusion

We can create a height converter app easily with React and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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