Categories
React Projects

Create a Temperature Converter 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 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.

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 *