Material ui textfield wont clear after state change

I have a simple Text field which i want to clear when a button is pressed, for some reason is not working.. i pass the state as value to the textfield and change the state but the field stays filled...

sandbox https://codesandbox.io/s/eager-edison-yqirl?file=/src/App.js

export default function App() {
  const [state, setState] = useState();
  const clear = () => {
    setState();
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <TextField value={state} id="outlined-basic" variant="outlined" />
      <button onClick={() => clear()}>clear</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Upvotes: 0

Views: 1591

Answers (1)

SaimumIslam27
SaimumIslam27

Reputation: 1184

import React, { useState } from "react";
import "./styles.css";
import { TextField } from "@material-ui/core";
export default function App() {
  const [state, setState] = useState("");
  const clear = () => {
    setState("");
  };
  const handleChange = (event) => {
    setState(event.target.value);
  };
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <TextField
        value={state}
        id="outlined-basic"
        variant="outlined"
        onChange={handleChange}
      />
      <button onClick={() => clear()}>clear</button>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Upvotes: 2

Related Questions