-1

i am using material-ui for my project and i am doing function to reset text of input to empty when clicking an outer button, it seem like not worked out

this is my code

var inputRef = useRef(null)

assign inputRef to the input field to access DOM

<TextField label="Student Name" ref={inputRef} />

an outer button to reset text field to empty when click it:

  <Button variant="contained" color="primary" onClick={() => {inputRef.current.value = ""}}>
    Reset
  </Button>

and it unchanged, if it is possible, please modify the code in the codesandbox link here, thank you so much

Tam Do
  • 181
  • 4
  • 15

2 Answers2

1

You do incorrectly in step: assign inputRef to the input field to access DOM. It should be a ref of input element instead text field component (actual a div).

You should have state for value of Textfield Or using inputRef instead of ref to point to input element. Demo

import React, { useRef } from "react";
import { TextField, Button } from "@material-ui/core";
import "./styles.css";

export default function App() {
  var inputRef = useRef(null);
  return (
    <div className="App">
      <TextField label="Student Name" inputRef={inputRef} />
      <Button
        onClick={() => {
          console.log(inputRef);
          inputRef.current.value = "";
        }}
        variant="contained"
        color="primary"
      >
        Reset
      </Button>
    </div>
  );
}
Viet Dinh
  • 1,871
  • 1
  • 6
  • 18
0

useRef can be used on html DOM elements(<input/>). To pass ref to Material-UI input you should use inputRef property.

Please refer How can I use ref in TextField

 var inputRef = useRef(null);

<TextField label="Student Name" inputRef={inputRef} />

demo

Rohitha
  • 776
  • 3
  • 8