Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
¿Cómo cambiar la imagen de fondo con React cuando se carga una página?

¿Cómo cambiar el fondo de la página cuando se carga sin tener que hacer clic en el botón?

 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> );

pero setBackground(list)} no lee la matriz y el evento onLoad no funciona cuando se recarga la página.

¡Gracias por cualquier ayuda!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Como se mencionó anteriormente, la solución requiere localStorage , useEffect , useRef . Toda la lógica está dentro de useEffect , porque cuando el componente se está montando, aquí ocurre toda la magia. ejemplo de trabajo

  1. Inicializar un número absoluto con useRef
  2. Intentando obtener valor de localStorage , si está vacío, establecemos el valor predeterminado. Y en el mismo lugar, comprobamos el índice de la matriz.
  3. La segunda vez evita el cheque y aumentamos el valor obtenido y el número absoluto.
  4. Luego, envía el resultado al almacenamiento estatal y local.

Aplicación.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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!