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

239
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
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