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

227
Visualizações
React: Setting useState() hook clears out input fields?

Whenever I set a state in my React app, it clears out my inputs (check box, numbers). Here's a very barebones version that illustrates the issue.

import React, { useState } from "react";
export default function App() {
  const [dummy, setDummy] = useState(false);

  function handleMint() {
    setDummy((dummy) => !dummy);
  }

  const MintBTN = () => (
    <div>
      <div>
        <input className="form-control" type="number" max="20" min="1" />
        <div>
          <input type="checkbox" />
        </div>
      </div>

      <div>
        <button onClick={handleMint}>mint</button>
      </div>
    </div>
  );
  return <MintBTN />;
}

You can try it out yourself. Add numbers and click the check box and hit mint. Whamo-bamo, your inputs magically disappear.

https://codesandbox.io/s/friendly-buck-6g6oh?file=/src/App.js:0-499

I figure there's something I'm doing wrong that I just don't see yet. I need to be able to click the button or do an onChange event for the inputs without them clearing out. For some reason setting state is also making my page styles freak out. Not sure what's going on. Some of my key dependencies if those are helpful. Thanks.

"react": "^17.0.2",
"webpack": "^4.19.1"
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Each time you set a state (setDummy), the component is rerendered and will reset you're inputs because they are uncontrolled. You need to make them controlled by using state hooks for those inputs.

import React, { useState } from "react";
export default function App() {
  const [dummy, setDummy] = useState(false);
  const [number, setNumber] = useState(0);
  const [checked, setChecked] = useState(false);

  function handleMint() {
    setDummy((dummy) => !dummy);
  }

  return (
    <div>
      <div>
        <input
          className="form-control"
          type="number"
          max="20"
          min="1"
          value={number}
          onChange={e => setNumber(e.target.value)}
        />
        <div>
          <input
            type="checkbox"
            checked={checked}
            onChange={e => setChecked(e.target.checked)}
          />
        </div>
      </div>

      <div>
        <button onClick={handleMint}>mint</button>
      </div>
    </div>
  );
}

Notice the value and checked properties. They are being set by the hook value on each render. Now, notice the onChange property. Each time you interact with the input it will update the hook value and rerender the component. By letting React manage the value and checked properties, it will save the values of the inputs in each hook.

Take a look at Controlled Components and State Hooks

Update

Removed MintBTN function as Nicholas Tower pointed out

about 4 years ago · Juan Pablo Isaza Relatório

0

You are creating the MintBTN component inside of your App component. This does not work. Every time App renders, you create a brand new type of component. It may have the same text as the previous one, but it's a new type, so react needs to unmount the old one, and mount a new one, which resets the values of stored in any dom elements, and resets any react state.

Instead, create the component once outside of app.

export default function App() {
  const [dummy, setDummy] = useState(false);

  function handleMint() {
    setDummy((dummy) => !dummy);
  }

  return <MintBTN onClick={handleMint} />;
}

const MintBTN = ({ onClick }) => {
  return (
    <div>
      <div>
        <input className="form-control" type="number" max="20" min="1" />
        <div>
          <input type="checkbox" />
        </div>
      </div>

      <div>
        <button onClick={handleMint}>mint</button>
      </div>
    </div>
  );
};
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