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

124
Visualizações
Im trying to create a new div on click but for some reason my dom is never updating. Why is this not working?

I am unsure what I am doing wrong..If I switch the state to a counter it works, but I need it to be an array of objects to store different values for each div. Not sure why the dom never updates.

import "./styles.css";
import { useState } from "react";

// The parent component
const App = () => {
  const [textBoxDivs, setTextBoxDivs] = useState([]);

  const addNewTextBox = () => {
    const textboxes = textBoxDivs;
    const numOfTextBoxDivs = textBoxDivs.length;
    const newTextBox = { id: `div${numOfTextBoxDivs + 1}` };
    textboxes.push(newTextBox);
    setTextBoxDivs(textboxes);
    console.log(textboxes, "boxes");
  };
  return (
    <div>
      <button onClick={() => addNewTextBox()}>Click me</button>
      {textBoxDivs.length > 0
        ? textBoxDivs.map((item, index) => (
            <div key={index} id={item.id}>
              text
            </div>
          ))
        : null}
    </div>
  );
};

export default App;

codeSandbox: https://codesandbox.io/s/friendly-water-wf4f5?file=/src/App.js:0-749

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

0

Because you are attempting to mutate existing state by pushing a new item to textBoxDivs, rather than providing a new state, breaking one of the fundamental rules of React.

Instead of pushing to your textBoxDivs array, provide a new copy of your state, with the new item inserted:

import "./styles.css";
import { useState } from "react";

// The parent component
const App = () => {
  const [textBoxDivs, setTextBoxDivs] = useState([]);

  const addNewTextBox = () => {
    const numOfTextBoxDivs = textBoxDivs.length;
    const newTextBox = { id: `div${numOfTextBoxDivs + 1}` };

    setTextBoxDivs((textBoxDivs) => ([
        ...textBoxDivs,
        newTextBox
    ]));
  };
  return (
    <div>
      <button onClick={() => addNewTextBox()}>Click me</button>
      {textBoxDivs.length}
      {textBoxDivs.length > 0
        ? textBoxDivs.map((item, index) => (
            <div key={index} id={item.id}>
              text
            </div>
          ))
        : null}
    </div>
  );
};

export default App;

Reading:

  • Array spreading

I should note that there's nothing inherently wrong with using push in this scenario, the issue is that you are pushing to existing state. You could just as easily do

// Still creating a new state from the current state
const newTxtBoxDivs = [...textBoxDivs];

newTxtBoxDivs.push(newTextBox);

setTextBoxDivs(newTxtBoxDivs);

For the same effect. The key take-away is that newTxtBoxDivs does not refer to the same object as textBoxDivs, it refers to a copy of it.

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