Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

281
Vistas
How to change background image in React depending on input value?

I want to change the background image of a site based on the input the user types in. For example, if the user types in New York or New York City or NYC, the background image changes to a picture of NYC.

Right now, I have a div tag with a class and in a CSS file, the background image is set to a url from the internet. I've figured out that you need to import the file that you want to use as a background image if you want to set the inline style in the .jsx file but I think this would be a tedious method since I have hundreds of images that I want to render based on the input. So without using jQuery (I saw another post similar to this question but in jQuery and I've read that using jQuery with React is not a great idea and I'm not even sure I could make it work with my React setup) how would you change the background image of a div depending on an input value?

function App() {

const [name, setName] = useState('');
const [headingText, setHeadingText] = useState('City');

function handleChange(event){
    setName(event.target.value);
  }

function handleKeyDown(event){
    
    if(event.key === 'Enter'){

      setHeadingText(name);
    }
  }

return (
    <div className="App">
      <header className="App-header">

        <input value={name} onKeyDown={handleKeyDown} onChange={handleChange} type="search" placeholder="Search for a city"></input>
        
      </header>
      
    </div>
      
  );
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can make use of inline styles of CSS as one of the methods, I've re-written your code below.

function App() {
const [name, setName] = useState('');
const [headingText, setHeadingText] = useState('City');

function handleChange(event){
    setName(event.target.value);
 }
function handleSubmit(event){  
 setHeadingText(name)
  }

return (
    <div className="App" style={{ backgroundImage:`url(${name}.jpg)` }}>
      <header className="App-header">
        <input value={name}  onChange={handleChange} type="search" placeholder="Search for a city"/>
        <button onClick={handleSubmit}>Enter</button>
      </header>
    </div>
      
  );
}

The backgroundImage URL, should be pointing to a particular file/directory in your project that contains the image, or a link to a jpg file that contains the image.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Some websites give API for searching wallpapers and background images that you can use. One of them is Unsplash. Please register as a developer, make an application (or use Demo app) on that, and copy your ACCESS_KEY and past in code (YOUR_ACCESS_KEY) to send your request to Unsplash API and get wallpapers.

import axios from "axios";
import { useState } from "react";
import "./styles.css";

export default function App() {
  const [backgroundUrl, setBackgroundUrl] = useState("");
  const [searchInput, setSearchInput] = useState("");
  const [loading, setLoading] = useState(false);

  const searchBackground = () => {
    if (!searchInput) {
      alert("There is no any word to searching!");
      return;
    }
    setLoading(true);

    // Send request to Unsplash API for searching your word and get wallpapers of that.
    axios
      .get("https://api.unsplash.com/search/photos/", {
        params: {
          client_id: "YOUR_ACCESS_KEY",
          query: searchInput
        }
      })
      .then((res) => {
        const results = res?.data?.results;
        const randomBackground =
          results[Math.floor(Math.random() * results.length)];
        setBackgroundUrl(randomBackground.links.download);
      })
      .catch((err) => {
        console.log(err);
      })
      .then(() => setLoading(false));
  };

  if (loading) return <div>Loading background...</div>;

  return (
    <div className="App">
      <h1>Please enter background title</h1>
      <input
        value={searchInput}
        onChange={(e) => setSearchInput(e.target.value)}
      />
      <button onClick={searchBackground}>Search</button>

      <div style={{ marginTop: 50 }}>
        {backgroundUrl && (
          <img src={backgroundUrl} alt="background" width={"100%"} />
        )}
      </div>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda