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

139
Vistas
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 Respuestas
Responde la pregunta

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