Skip to content

Instantly share code, notes, and snippets.

@gunar
Created April 3, 2019 18:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gunar/fc3f65f84ecd3b1878a3dc582a14508b to your computer and use it in GitHub Desktop.
Save gunar/fc3f65f84ecd3b1878a3dc582a14508b to your computer and use it in GitHub Desktop.
Reset Uncontrolled Forms by Forcing React to Rebuild the DOM.
import React, { useState, createRef } from "react";
const Form = () => {
const emailRef = createRef<HTMLInputElement>()
return (
<div>
Email:
<input type="text" ref={emailRef}/>
<button
onClick={() => {
// This check is necessary because in theory we could hit this
// code even though React is still rebuilding the DOM.
if (emailRef.current) {
window.alert(`Your email is "${emailRef.current.value}"`)
}
}}
>
Go
</button>
</div>
);
};
export {
Form,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment