0

I'm stumped on this.

I have a controlled input (I'm using Material-UI TextField and Autocomplete).

I'm happy for the component to control its own value, except I want to be able to clear the input.

How would I do that?

function App() {
  const handleClick = useCallback(() => {
    //Do what?
  }, []);
  return (
    <div className="App">
      <TextField label="I'm a controlled input" />

      <button onClick={handleClick}> Click to clear</button>
    </div>
  );
}

(Code Sandbox)

The reason I don't want to implement the state of this myself, is because the autocomplete + textfield is quite complex, I figure there must be a simpler solution.

Is there a way I could mimik a keyboard event to clear the textfield for example?

dwjohnston
  • 11,163
  • 32
  • 99
  • 194

1 Answers1

0

Since you are not explicitly setting the value of the TextField then it's not really a controlled input.

You can set the value of the TextField to a state, then clear the state when the button is clicked:

function App() {
  const [text, setText] = useState("");
  const handleClick = useCallback(() => {
    setText("");
  }, []);
  return (
    <div className="App">
      <TextField label="I'm a controlled input" value={text} onChange={(e) => setText(e.target.value)} />

      <button onClick={handleClick}> Click to clear</button>
    </div>
  );
}

Demo

If you don't wanna use a state, you can use the prop inputRef of TextField to get a reference to the input then clear it manually:

function App() {
  const ref = useRef();
  const handleClick = useCallback(() => {
    ref.current.value = "";
  }, []);
  return (
    <div className="App">
      <TextField label="I'm an uncontrolled input" inputRef={ref} />

      <button onClick={handleClick}> Click to clear</button>
    </div>
  );
}

Demo2

Hamza El Aoutar
  • 5,292
  • 2
  • 17
  • 23