Be Free Studios

FREESTUDIOS

design | development | strategy

Home

|

Blog

|

About

|

Services

|

Contact
Focusing Form Elements with React

Focusing Form Elements with React

Focusing input, or other form elements, with HTML and Javascript is pretty straight forward. But, what's the proper way to do this with React?

By: Burton Podczerwinski

·

1 minute read

If you've built an html form before, you've probably tried to programmatically focus an element. Wether it's on page load, or after an error, it's the same. First you select the element, then focus it with Javascript. Something like the following...

document.getElementById("myElement").focus();

That's great, but what are we supposed to do with a modern framework like React? Directly accessing and manipulating the DOM is considered an anti-pattern in React, so ughh... what now?

Enter stage left: the useRef() hook. Let's take a look.

Ref's can be used to access DOM nodes and ReactNodes that have already been rendered. Here are the steps...

  1. Create a constant to track your ref.

  2. Add ref-attribute to element that you want to track.

  3. Implement .focus()

  4. Profit.

javascriptreactforms

Fully Custom -- Never Wordpress -- Never TemplatedWe utilize the latest bleeding edge technology, tooling, design principles, and methodologies in the modern digital landscape.

Technology

React.jsAngular.ioVue.jsGraphQLplus many more...

Infrastructure

GitHubAtlassian SuiteNetlifyAWSplus many more...