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

141
Visualizações
React changing useState not rendering component when using map to generate elements

here is my case, i'm loading SVG file and rendering it to the screen. i would like to change to colors of the svg file. (svg file contains 500 objects)

all works good, and seems like the state has been changed but the component are not been rendered. i think this is because i'm using the map in order to generate the elements - here is my code:

const Sim = () => {

    const [elements, setElements] = useState([]);

    const loadSVG = (e) => {
       ...
       ...
            newElements = newElements.map(x=> ({
                data: x,
                color: '#0a22a0'
            }))

            setElements(newElements)
        };
    }

    const rndColors = () => {

        elements.forEach(x=> {
            x.color = "#" + Math.floor(Math.random()*16777215).toString(16);
        })

        setElements(elements)
        console.log(elements)
        
    }

    return (
        <div>
            <Button style={{marginBottom: 10, maxHeight: 20}} size="small" variant="outlined" onClick={rndColors}>RND Colors</Button>
            <svg
                viewBox="0 0 2000 2000"
                version="1.1"
                x="0px"
                y="0px"
                style={{maxHeight:700}}
            >
            {elements.map((x,i) =>
                <SVGElement
                    data={x.data}
                    index={i}
                    color={x.color}
                />)
            }
            </svg>

        </div>
    )
}

i could clearly see in the logs the colors are changed, but the actual svg color is not changed (only after i change something in the code the page refreshed - i can see the new colors)

How can i make sure that once i click the button all of the colors of the svg will be changed? something is not triggering here the render cycle of the elements.. what do i missing here?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

elements.forEach((x) => {
  x.color = "#" + Math.floor(Math.random() * 16777215).toString(16);
});

setElements(elements);

You are mutating the state above, you should always update state in immutable way. You can rewrite above code to:

setElements(
  elements.map((x) => ({
    ...x,
    color: "#" + Math.floor(Math.random() * 16777215).toString(16),
  }))
);
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