I am using document.getelementbyID().reset(); to reset form values. But I am receiving an error in typescript.
Property 'reset' does not exist on type 'HTMLElement'.
I am using this feature:
const resetButton = () => {
document.getElementById('compliance').reset();
}
<button onClick={resetButton}>
Reset
</button>
This feature worked in javascript but not in typpescript.
How can I use it. I have tried these methods but none work.
1.
(<HTMLInputElement>document.getElementById('compliance)).reset;
I received this error.
JSX element 'HTMLInputElement' has no corresponding closing tag.
let inputreset = (document.getElementById('compliance) as HTMLInputElement).reset;
I received this error.
Property 'reset' does not exist on type 'HTMLInputElement'.
CodePudding user response:
If you are trying to reset a form, cast it to HTMLFormElement
, which does have the reset
method (TS playground):
const resetButton = () => {
(document.getElementById('compliance') as HTMLFormElement).reset();
}
A solution that would be more React friendly is to use a ref:
const form = useRef<HTMLFormElement>();
const resetButton = () => {
formRef.current?.reset(); // note conditional chaining `?.`
}
return (
<form ref={formRef}>
{/* Other form controls */}
<button onClick={resetButton}>
Reset
</button>
</form>
)
The best solution would be to set button type to reset
, and then you won't need the function at all:
<button type="reset">
Reset
</button>