Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

92
Visualizações
How can I change background src dynamically in react based on api response?

I`m new to react, I tried to build a simple weather app, I made a full-screen video background and I want it to change the src dynamically based on the response I'm getting from the API,

here is my code:

import { useEffect, useState } from "react";
import { Background } from "./components/Background";

const api = {
  key: "",
  base: "https://api.openweathermap.org/data/2.5/",
};

function App() {

const [query, setQuery] = useState("");
const [weather, setWeather] = useState({});
const [backgroundVideo, setBackgroundVideo] = useState("");

const search = (e) => {
    if (e.key === "Enter") {
      fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
        .then((res) => res.json())
        .then((result) => {
          setWeather(result);
          setBackgroundVideo(`${result.weather[0].description}`);//clear sky
          setQuery("");
        });
    }
  };
  
  return (
    <div className="bg">
      {/**Video Background */}
      {typeof weather.main !== "undefinde" &&
      typeof weather.sys !== "undefined" ? (
        <video autoPlay loop muted className="vid">
          <source
            src={`/videos/${backgroundVideo}.mp4`} // /videos/clear sky.mp4
            type="video/mp4"
          />
          
        </video>
      ) : (
        ""
      )}
 }

I'm getting all the data I want but it doesn't work, when I refresh the page there is no video, when I search for the first city it works(London -> scattered clouds), but if I searched for another city (Sanaa -> few clouds) it stays the same as before, although when I see the video source from dev tools it was updated!

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda