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

241
Vistas
why doesn't my background image change on click

i'm doing a react project, and in my project there's a functionality that changes the backgroundImages on click, but the image doesn't show. Something changes, but the image doesn't show. And i'm positive i got the right path. I would appreciate som insight. Thank you in advance. Here is the code:

export function theme_switcher(){
    let value = true;
    let btn_theme_switcher = document.getElementById("theme-switcher");
    function toggle(){
        if(value){
            black_theme();
            value = false;
        } else {
            white_theme();
            value = true;
        }
    }
    btn_theme_switcher.addEventListener("click", () => {
        toggle();
    })
}

function white_theme(){
    console.log("white");
    document.getElementById("background-img").style.backgroundImage = 'url("../images/bg-mobile-dark.jpg")';
    document.getElementById("background-img").style.backgroundPosition = "center";
    document.getElementById("background-img").style.backgroundSize = "cover";
}
function black_theme(){
    console.log("black");
    document.getElementById("background-img").style.backgroundImage = 'url("../images/bg-mobile-dark.jpg")';
    document.getElementById("background-img").style.backgroundPosition = "center";
    document.getElementById("background-img").style.backgroundSize = "cover";
}

This is in another file:

export default function ReactUseEffect(){
    React.useEffect(() => {
        theme_switcher();
        default_task_counter();
        delete_listener();
        completed_listener();
    });
    return(null);
}

Here is the live version: https://todo-list-lac-ten.vercel.app/ Here is my github: https://github.com/OrlandoVSilva/todo-list.git

*Forgot to tell you where to click. Its in the moon icon. Sorry!

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

0

That's mostly because you used value as a variable. You should use useEffect for handling component states. But such effect can also be achieved using css

JS:

function ThemeSwitcher() {
    const [dark, setDark] = useState(false);

    return (
        <div className='...' >
            <div className={`bg${dark ? ' bg--dark' : ''}`} />
        </div>
    );
}

CSS:

.bg {
    background-position: center;
    background-size: cover;

    background-image: url("../images/bg-mobile-white.jpg");
}

.bg.bg--dark {
    background-image: url("../images/bg-mobile-dark.jpg");
}

Also while using React you should really forget about methods like getElementbyId or addEventListener as it has way better solutions for this.

about 4 years ago · Juan Pablo Isaza Denunciar

0

theme_switcher is called via React.useEffect but I think callbacks should be called via React.useEffect as well so instead of calling black_theme();, try calling React.useEffect(black_theme);
Also all this is probably against every common React practice
Even if let's say background-img is somehow outside of your React scope (whatever this means) then at least value should be a state variable

about 4 years ago · Juan Pablo Isaza Denunciar

0

i appreciate the help ALOT, but i managed to get ot work with this:

import backgroundPic from "../images/bg-mobile-dark.jpg"
//-----------------------------------------------
export default function ContentHeaders(){
    const change_theme =  () => {
        let background = document.getElementById("background")
        background.style.backgroundImage = `url(${backgroundPic})`
    }
    return(
        <div id = "header">
            <h1>TODO</h1>
            <div id = "theme-switcher" onClick = {change_theme}></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