'How to clear the value of an input field in a functional component without using state?

I have an input field and I handle the input via onKeyUp (as I need to access event.which). This works great so far as I just grab the content of the input via event.target.value but I run into issues when I try to reset the value of the input field.

I'm using functional components, so accessing the input via refs isn't possible and all examples I found with useRef just show how to focus the input field but not how to clear it.

I forgot to mention that I'm using Material-UI.



Solution 1:[1]

My current solution uses onChange to update the state of the value and onKeyUp to handle the input (and eventually resetting the value):

export default function TypingArea() {
const [inputValue, setInputValue] = useState('');

const handleChange = event => {
  setInputValue(event.target.value);
};

const handleInput = event => {
  // access event.which for the keycode and eventually clear the inputfield value
  setInputValue('');
}  

return (
<TextField
  onChange={handleChange}
  onKeyUp={handleInput}
  type='text'
  value={inputValue} />);
}

I might run into issues with this setup as I'm not sure who runs first, onChange or onKeyUp, but it works for now.

Solution 2:[2]

you can do e.target.reset considering you are using functional component.

 const [state, setState] = React.useState({ username: "", password: "" });

  const handleSubmit = e => {
    e.preventDefault();
    console.log(state);
    

e.target.reset();

  };
const handleChange = e => {
    setState({
      ...state,
      [e.target.name]: e.target.value
    });
  };
  return (
    <div className="App">
      <h1>Log In</h1>
      <form onSubmit={handleSubmit}>
        <input
          className="userInput"
          name="username"
          type="text"
          placeholder="username"
          onChange={handleChange}
        />
        <br />
        <input
          className="userInput"
          name="password"
          type="password"
          placeholder="password"
          onChange={handleChange}
        />
        <br />
        <input className="userSubmit" type="submit" value="Log In" />
      </form>
    </div>
  );
}

Solution 3:[3]

const [tasks, setTasks] = useState([]);
const [input, setInput] = useState(' ');


Const addTask = () => {
       setTasks([...tasks, input])
       SetInput(' ')

}
return (
  <button onClick={addTasks}/>Add Task <button/>
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Aarthi Chandrasekaran
Solution 3 David Salomon