Preview:
import React, { useState, useEffect } from "react";

import "./style.css";

function App() {
  const [data, setData] = useState({});
  const [unit, setUnit] = useState("fahrenheit");

  const fetchData = async (lat, lon) => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=ce309858c9580a2f86ac0e0f45374afb`;
    const response = await fetch(url);
    const result = await response.json();
    setData(result);
    console.log(result);
  };

  function myGeoLocator() {
    navigator.geolocation.getCurrentPosition((position) => {
      const lat = position.coords.latitude;
      const lon = position.coords.longitude;
      fetchData(lat, lon);
    });
  }

  const kelvinToFahrenheit = (temp) => {
    return (((temp - 273.15) * 9) / 5 + 32).toFixed(2);
  };

  const kelvinToCelsius = (temp) => {
    return (temp - 273.15).toFixed(2);
  };

  const handleUnitChange = () => {
    setUnit((prev) => (prev === "celsius" ? "fahrenheit" : "celsius"));
  };

  return (
    <div className="app">
      <div className="temperature">{data.name ? data.name : null}</div>

      <div className="temperature">
        {data.main ? (
          <>
            {" "}
            {unit === "celsius"
              ? kelvinToCelsius(data.main.temp)
              : kelvinToFahrenheit(data.main.temp)}
            {unit === "celsius" ? "°C" : "°F"}
          </>
        ) : null}
      </div>

      <button className="button" onClick={myGeoLocator}>
        Get Weather
      </button>

      <button className="button" onClick={handleUnitChange}>
        Celsius/Fahrenheit
      </button>
    </div>
  );
}

export default App;
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter