Skip to content

Commit 696f334

Browse files
committed
ReactDOM.requestFormReset
This adds a React DOM method called requestFormReset that schedules a form reset to occur when the current transition completes. Internally, it's the same method that's called automatically whenever a form action is submitted. It only affects uncontrolled form inputs. See facebook#28804 for details. The reason for the public API is so UI libraries can implement their own action-based APIs and maintain the form-resetting behavior, something like this: ```js function onSubmit(event) { // Disable default form submission behavior event.preventDefault(); const form = event.target; startTransition(async () => { // Request the form to reset once the action // has completed requestFormReset(form); // Call the user-provided action prop await action(new FormData(form)); }) } ```
1 parent f96f89f commit 696f334

File tree

5 files changed

+443
-78
lines changed

5 files changed

+443
-78
lines changed

packages/react-dom-bindings/src/client/ReactFiberConfigDOM.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1954,13 +1954,19 @@ function flushSyncWork() {
19541954
}
19551955

19561956
function requestFormReset(form: HTMLFormElement) {
1957-
previousDispatcher.r(/* requestFormReset */ form);
19581957
const formInst = getInstanceFromNodeDOMTree(form);
1959-
if (formInst !== null) {
1958+
if (
1959+
formInst !== null &&
1960+
formInst.tag === HostComponent &&
1961+
formInst.type === 'form'
1962+
) {
19601963
requestFormResetOnFiber(formInst);
19611964
} else {
1962-
// TODO: What if none of the dispatchers find a matching form instance?
1963-
// Should we detect this in dev and warn?
1965+
// This form was either not rendered by this React renderer (or it's an
1966+
// invalid type). Try the next one.
1967+
//
1968+
// The last implementation in the sequence will throw an error.
1969+
previousDispatcher.r(/* requestFormReset */ form);
19641970
}
19651971
}
19661972

packages/react-dom/src/ReactDOMSharedInternals.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,16 @@ export type ReactDOMInternalsDev = ReactDOMInternals & {
2929

3030
function noop() {}
3131

32+
function requestFormReset(element: HTMLFormElement) {
33+
throw new Error(
34+
'Invalid form element. requestFormReset must be passed a form that was ' +
35+
'rendered by React.',
36+
);
37+
}
38+
3239
const DefaultDispatcher: HostDispatcher = {
3340
f /* flushSyncWork */: noop,
34-
r /* requestFormReset */: noop,
41+
r /* requestFormReset */: requestFormReset,
3542
D /* prefetchDNS */: noop,
3643
C /* preconnect */: noop,
3744
L /* preload */: noop,

0 commit comments

Comments
 (0)