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

150
Vistas
How can update the DOM if the state changes?

I've created the box container dynamically according to the input changes.

  1. If I entered 1, it will create one box
  2. If I change the input lets say 2, its create 3 box but it should create 2
import React from 'react';
import './style.css';

export default function App() {
  const [value, setValue] = React.useState();
  const boxRef = React.useRef();

  function createBox() {
    const div = document.createElement('div');
    div.classList.add('mystyle');
    div.style.backgroundColor = 'white';
    div.addEventListener('click', () => {
      let boxColor = div.style.backgroundColor;
      if (boxColor === 'white') {
        div.style.backgroundColor = 'red';
      } else {
        div.style.backgroundColor = 'white';
      }
    });
    return div;
  }

  React.useEffect(() => {
    for (let i = 0; i < value; i++) {
      const boxElement = createBox();
      boxRef.current.appendChild(boxElement);
    }
  }, [value]);

  function handleBoxCreate({ target: { value } }) {
    setValue(value);
  }

  return (
    <div>
      <h1>BOX CREATE</h1>
      <input type="number" name="boxInput" onChange={handleBoxCreate} />
      <div ref={boxRef}  />
    </div>
  );
}
/* style.css */
.mystyle {
  width: 30px;
  height: 30px;
  border: 2px solid black;
  display: inline-block;
  padding: 2px;
  margin-right: 5px;
}

Do I need to cleanup the dom. if so how to do it?. or is there any better way to implement the same.

Please help. ty:)

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

0

You should avoid doing direct manipulations on the DOM. Instead create a "Box" react component and render it based on the amount of your value state.

import React from "react";
import "./styles.css";

const Box = () => {
  const [color, setColor] = React.useState("white");

  const onClick = () => {
    if (color === "white") {
      setColor("red");
    } else {
      setColor("white");
    }
  };
  return (
    <div
      className="mystyle"
      style={{ backgroundColor: color }}
      onClick={onClick}
    />
  );
};

export default function App() {
  const [value, setValue] = React.useState(0);

  function handleBoxCreate({ target: { value } }) {
    setValue(Number(value));
  }

  return (
    <div>
      <h1>BOX CREATE</h1>
      <input type="number" name="boxInput" onChange={handleBoxCreate} />
      {[...Array(value)].map((e, i) => (
        <Box key={i} />
      ))}
    </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