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

182
Vistas
How to change background-image with React when a page is loading?

How to change the background of the page when it loads without having to click the button?

import img1 from '../images/img1.jpg';
import img2 from '../images/img2.jpg';
import img3 from '../images/img3.jpg';

const [background, setBackground] = useState(img1);

const list = [img1, img2, img3];

const css = {
    backgroundImage: `url(${background})`,
};

return (
    <div style={css}>
        <button onLoad={() => setBackground(list)}>Change background</button>
    </div>
);

but setBackground(list)} does not read the array and the onLoad event does not work when the page is reloaded.

thanks for any help!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As mentioned above the solution requires localStorage, useEffect, useRef. All logic is inside useEffect, because when the component is mounting all the magic happens here. working example

  1. Initialize an absolute number with useRef
  2. Trying to get value from localStorage, if is empty then we set default value. And the same place, we checking the array index.
  3. Second time avoid the check and we increace gotted value andabsolute number.
  4. Then sending result to state and localStorage

App.js

import { useState, useEffect, useRef } from "react";

export default function App() {
  const img1 = "https://dummyimage.com/400x200/a648a6/e3e4e8.png";
  const img2 = "https://dummyimage.com/400x200/4e49a6/e3e4e8.png";
  const img3 = "https://dummyimage.com/400x200/077d32/e3e4e8.png";

  let [lsNum, setLsNum] = useState(0);
  // Absolute number '1'
  let count = useRef(1);

  const list = [img1, img2, img3];

  useEffect(() => {
    // Get value from localStorage, transform to number
    const lS = Number(localStorage.getItem("image"));
    // Check! If localStorage have number 2 / more
    // Set number 0
    if (lS >= 2) {
      localStorage.setItem("image", 0);
      return;
    }
    // Get absolute number and increase with number from localStorage
    count.current = count.current + lS;
    // Set result to state
    setLsNum(count.current);
    // Set the resulting number to localStorage
    localStorage.setItem("image", count.current);
  }, []);

  const css = {
    height: "200px",
    width: "400px",
    display: "block",
    backgroundImage: `url(${list[lsNum]})`, // index change
    backgroundPosition: "center",
    backgroundSize: "cover",
    border: "1px solid red"
  };

  return (
    <div className="App">
      <div style={css}></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