Home > Net >  How to clear n number of input fields dynamically on a single button click in react
How to clear n number of input fields dynamically on a single button click in react

Time:09-01

const { useState, useEffect } = React;
const Thingy = ({ ...props }) => {
  const [tenure, setTenure] = useState(null);
  // state to hold tenure-dates (array of varying size)
  const [tnDates, setTnDates] = useState(null);

  const handleTenureChange = ev => setTenure(ev.target.value);

  useEffect(() => setTnDates(
    (tenure && tenure > 0)
      ? ([...Array( tenure).keys()].map(
        id => ({ id, tenureDate: '' })
      )) : null
  ), [tenure]);


  const handleDateChange = ev => {
    const idx = ev.target.id;
    const val = ev.target.value;
    setTnDates(prev => {
      const nd = [...prev];
      nd[idx].tenureDate = val;
      return nd;
    });
  };

above is the snippet for rendering tenure number of tenuredata where tenure is input from user. i want to clear all the tenure data input fields on a single button click. please help on this.

CodePudding user response:

Since the input fields are presumably the states of both

const [tenure, setTenure] = useState(null);
const [tnDates, setTnDates] = useState(null);

To 'clear' the above state you need to reset it to it's original falsy value.

Since both the states you want to set are initially set to null you simply need to set their state to null again.

// button that clears the form fields
<button onClick={() => { 
setTenure(null); 
setTnDates(null);
}

CodePudding user response:

Make sure you are using controlled components.

const handleClearInputs = () => {
  setTenure(null)
  setTnDates(null);
}

return(
  <input value={tenure} />
  <input value={tnDate} />
  <button onClick={handleClearInputs}>Clear</button>
)
  • Related