Temperature Converter

Question

Build a simple temperature converter widget that contains two text inputs temperatures in Celsius and Fahrenheit respectively, allowing for conversion between the temperature scales.

Requirements

  • Initially, both fields are empty. When a number value is entered into a text input, the other input will be calculated and reflected.

  • Round to 4 decimal places where necessary.

  • If a non-numerical string is entered into one input, the other input will be blank.

The last two requirements might not be given to you during interviews, you're expected to clarify.

P.S. To convert temperatures in degrees Celsius to Fahrenheit, multiply by 1.8 (or 9/5) and add 32.

Here's an example of Google's temperature converter (ignore the bottom row showing the formula):

Answer

import {useState,useEffect} from "react"
import './styles.css';

export default function App() {

  const convertToFahrenheit = (celsiusState) => {
    // return parseFloat(((celsiusState*1.8)+32).toFixed(4))
    return  (celsiusState*1.8)+32
  }

  const convertToCelsius = (fahrenheitState) => {
    return parseFloat(((fahrenheitState-32)/1.8).toFixed(4))
    // return (fahrenheitState-32)/1.8
  }

  const [celsius, setCelsius] = useState();
  const [fahrenheit, setFahrenheit] = useState();
  
  const handleCelsiusChange = (e) => {
    if(e.target.value !== "") {
    setCelsius(e.target.value)
    } else {
      setCelsius(e.target.value)
    }
  }

  const handleFahrenheitChange = (e) => {
    if(e.target.value !== "") {
    setFahrenheit(e.target.value)
    } else {
      setFahrenheit(e.target.value)
    }
  }

  useEffect(() => {
    if(fahrenheit !== "") {
    setCelsius(convertToCelsius(fahrenheit))
    } else {
      setCelsius("")
    }
  },[fahrenheit])

  useEffect(() => {
    if(celsius !== "") {
    setFahrenheit(convertToFahrenheit(celsius))
    } else {
      setFahrenheit("")
    }
  },[celsius])

  console.log(celsius)

  return (
    <div>
    Temperature Converter
    <div className="celsiusContainer">
    <input 
      type="number" 
      name="celsius" 
      value={celsius} 
      className="celsiusInput"
      onChange={(e) => handleCelsiusChange(e)} 
    />
    <label htmlFor="celsius">Celsius</label>
    </div>

    <div className="fahrenheitContainer">
    <input 
      type="number" 
      name="fahrenheit" 
      value={fahrenheit} 
      className="fahrenheitInput"
      onChange={(e) => handleFahrenheitChange(e)}  
    />
    <label htmlFor="fahrenheit">Fahrenheit</label>
    </div>
    </div>);
}

Doubt

https://www.loom.com/share/481676f467ba455995f583bf3bbdc2b2?sid=787e6732-437f-4618-befb-495198bc395b

Last updated