nathan
nathan

Reputation: 369

How can I remove an input and clear data in that input?

I am trying to create a button that add more input and remove input and when it remove the input it also clear all the data inside that input but the problem is when I remove that input but the data still stay. How can I fix that ?

Here is my code base:

const [inputs, setInputs] = useState(teamData.rules);

  useEffect(() => {
      setInputs(teamData.rules);
  }, [teamData]);

  // Add more input
  const addInputs = () => {
    setInputs([...inputs, { name: `rule-${inputs.length + 1}` }]);
  };

  // handle click event of the Remove button
  const handleRemoveClick = (index) => {
    const list = [...inputs];
    list.splice(index, 1);
    setInputs(list);
  };

  {inputs.map((data, index) => (
    <div className="agreement-form-grid" key={index}>
      <button
        className="agreement-remove-button"
        onClick={() => handleRemoveClick(index)}
      >
        <Remove />
      </button>
      <input
        type="text"
        defaultValue={teamData.rules[index]}
        name={`rule_${index}`}
        placeholder={`Rule ${index + 1}`}
        onChange={handleChange}
      />
    </div>
  ))}
  {inputs.length !== 4 && (
    <div className="team-agreement-add-rule">
      <button type="submit" onClick={addInputs}>
        <Add />
      </button>
    </div>
  )}

Update question add handleChange function:

  const handleChange = (event) => {
    const { name, value } = event.target;
    // Update state
    setUpdateTeamData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  }

Upvotes: 0

Views: 241

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13245

Define another function in your parent component to clear the data like below,

const clearInput = (dataName) => {
  setUpdateTeamData((prevState) => {
      delete prevState[dataName];
      return {
       ...prevState
      }
  });
}

In the child component, in the onClick of the remove button call this function as well

 <button
    className="agreement-remove-button"
    onClick={() => { handleRemoveClick(index); clearInput(`rule_${index}`)}}
  >
    <Remove />
 </button>

Before saving you can ignore empty inputs

Upvotes: 1

Related Questions