Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
¿Cómo puedo actualizar el DOM si cambia el estado?

Creé el contenedor de caja dinámicamente de acuerdo con los cambios de entrada.

  1. Si ingresé 1, creará un cuadro
  2. Si cambio la entrada, digamos 2, es un cuadro de creación de 3 pero debería crear 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; }

¿Necesito limpiar el dom. si es asi como se hace?. o hay alguna forma mejor de implementar lo mismo.

Por favor ayuda. ty :)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Debe evitar realizar manipulaciones directas en el DOM. En su lugar, cree un componente de reacción "Box" y renderícelo en función de la cantidad de su estado de valor.

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!