React Holiday

Come on, ref!

In the typical request-response lifecycle of an HTML page, submitted forms just dissolves into the impermanence of the web. In our case — where forms are submitted without a redirect — we have to reset forms on submit. Otherwise data will stick around, confusing the user.

In addition to the reset input — from yesterday — form elements have an API for imperatively resetting forms: formElement.reset().

We can call reset() on the target element of our onSubmit event handler:;

Easy-peasy. We’ve now reset the form on submit!

Take it home

We’ve reset this form, sure. But we’ve done it in a way that React has no control over — it’s all just DOM operations thru and thru.

If we want to reset the form in response to an event elsewhere in our app, we need to use a React ref — React’s tool for exposing direct access to the DOM. Open this CodeSandbox and change the reset functionality to use a ref instead of the event directly. You’ll find instructions in the comments.