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
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>
);
}
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} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.