How to clear an input after clicking the button?

Asked

Viewed 59 times

1

I’m having trouble finding a solution to clear the fields input after clicking the button calculate.

Follow code in simplified form

function EqBernoulli2 () {
  const [Pt, setPt] = useState('')
  const [Ps, setPs] = useState('')
  const [V, setV] = useState('')
  const [ρ, setρ] = useState('')
  const [resultado3, setResultado3] = useState()

  function calcular3 () {
    if (V == '') {
      let Prest = Math.sqrt(parseFloat((2 * (Pt - Ps)) / ρ))
      setResultado3(Prest)
    }
  }

  return (
    <div className='eqbernoulli'>
      <EqBernoulliM>
        <h2>Calculo: </h2>
        <p className='obs'>
          <i>Obs:</i>
        </p>
        <div className='input'>
          <label htmlfor='nome'>
            P<sub>t</sub> =
          </label>
          <input
            className='pressão1'
            type='number'
            id='pressão1'
            required='required'
            value={Pt}
            onChange={e => setPt(e.target.value)}
          />
        </div>
        <div className='input'>
          <label htmlfor='nome'>
            P<sub>s</sub> =
          </label>
          <input
            className='velocidade1'
            type='number'
            id='velocidade1'
            required='required'
            value={Ps}
            onChange={e => setPs(e.target.value)}
          />
        </div>
        <div className='input'>
          <label htmlfor='nome'>V =</label>
          <input
            className='altura1'
            type='number'
            id='altura1'
            required='required'
            value={V}
            onChange={e => setV(e.target.value)}
          />
        </div>
        <div className='input'>
          <label htmlfor='nome'>ρ =</label>
          <input
            className='pressão1'
            type='number'
            id='pressão2'
            required='required'
            value={ρ}
            onChange={e => setρ(e.target.value)}
          />
        </div>
        <button className='calcular2' id='calcular' onClick={calcular3}>
          Calcular
        </button>
        <div className='result' id='resultado'>
          {resultado3}
        </div>
      </EqBernoulliM>
    </div>
  )
}
  • Updating the state to an empty string does not work? For example, setPt(''). What you tried and what was the problem?

  • I did not try to update the status. What I imagined I could not put into practice. I am new in the area and in certain situations I feel a little stuck.

1 answer

2

Dealing with forms is complex. It is not at all that there are several libraries for this, as the React Hook Form, Formik, Unform etc..

If you don’t use a library to handle the form, there are two options left: controlled components (stately - useState) or uncontrolled components (with reference - useRef). In the case of this question, the first option is used, so I will explain only her.

Form with controlled components

In short, a input controlled has a face like this:

function Form() {
  const [valor, setValor] = React.useState('');
  return <input onChange={(e) => setValor(e.target.value)} value={valor} />;
}

This involves some concepts:

  • Value control: The value of input is controlled by the state (useState). If you do not update the status, the value of input does not update to the user.
  • Receiving the value: You receive the amount entered by the user through the event onChange, accessing the property target.value of the argument passed as an event (in the above code, e).
  • Displaying the value: You pass the value of your state to the input through property value. In the above example, value={valor}.

This is already correct in the question code. The question is: how to clear the input?

Once you have understood how storage, receiving and displaying the value of input, I hope you already know how to clean the input: just clear the state. See the example below:

function Form() {
  const [valor, setValor] = React.useState('');

  return (
    <form>
      <input onChange={(e) => setValor(e.target.value)} value={valor} />
      <button onClick={() => setValor('')} type="button">Limpar</button>
    </form>
  );
}

ReactDOM.render(<Form /> , document.querySelector("#app"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>

<div id="app"></div>

If you own several inputs, is not much different from the example, just clear all states:

function limparInputs() {
  setInput1('');
  setInput2('');
  setInput3('');
}
  • +1 @Mpimenta in your case, Voce could call limparInputs inside calcular3, right after the block if, but of course, assuming that it would have a treatment for cases of errors of values.

  • I managed to put a clean button calling cleanInputs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.