Search code examples
reactjsbackground-imageopenweathermapweather-api

Match background with users current weather conditions


I am new to React, trying to learn and I have this unsolvable problem. I have developed a weather app, I'm still working on it, but at this moment I am stuck for 3 days trying to have a background image that changes depending on the users weather conditions. I have tried something using the icon, from openweather API. I used the same method to get the icon (image from my folder) to match users weather conditions.

   import React from "react";
   export default function Background(props) {
const codeMapping = {
"01d": "clear-sky-day",
"01n": "clear-sky-night",
"02d": "cloudy-day",
"02n": "cloudy-night",
"03d": "cloudy-day",
"03n": "cloudy-night",
"04d": "cloudy-day",
"04n": "cloudy-night",
"09d": "shower-rain-day",
"09n": "shower-rain-night",
"10d": "rain-day",
"10n": "rain-night",
"11d": "thunderstorm-day",
"11n": "thunderstorm-night",
"13d": "snow-day",
"13n": "snow-night",
"50d": "fog-day",
"50n": "fog-night",
};
let name = codeMapping[props.code];
return (
<img
  className="background"
  src={`background/${name}.jpg`}
  alt={props.alt}
  size="cover"
/>
);
}

So... in order to get "icon" of the input city by the user I have to call "<Background cod={weatherData.icon} alt={weatherData.description} />" from the function "Search" which is the function handling the submit form and running api call for input city. But the image is not showing(img1), but to have the img as a background I would call <Background> from my App function(img2), but in this case I will not have access to the real icon value from the input city. I should mention I have a folder in "src" called background and the images names match the codes name from the mapping. Thank you in advance!

current preview of my app
how I see in other documentation I should set a background


Solution

  • You can pass the code from Search.js as the state.

    App.js

    const codeMapping = {
        "01d": "clear-sky-day",
        "01n": "clear-sky-night",
    };
    
    export const App = () => {
    
        const [code, setCode] = useState(null) // <-- We'll update this from Search.js
        const [backgroundImage, setBackgroundImage] = useState("")
    
        useEffect(() => {
            // Set background value based on the code
            setBackgroundImage(codeMapping[`${code}`]) 
        }, [code]); // <-- useEffect will run everytime the code changes
    
        return (
            <div style={{
                height: '100px', 
                width: '100px',
                backgroundImage: `${backgroundImage || "defaultBackgroundImage"}`
            }}>
              <Search setCode={setCode} />
            </div>
        )
    }
    

    Search.js

    import { WeatherContext } from './App';
    
    export const Search = ({ setCode }) => {
      
      const handleClick = (apiResponse) => {
        // Some API call returning the actual code value here //
        setCode(apiResponse)
      }
      
      return (
        <input
          onClick={() => handleClick("01n")}
          type="button"
          value="Change city"
        />
      )
    }