Helping the user’s focus stay on the right place is a key part of the user experience. This is especially important for users who rely on screen readers or keyboard navigation. But even able users can benefit from a well-thought focus management experience.
Sometimes, the element you want to focus on only becomes available after a state update. For example:
function MyComponent() {const [show, setShow] = useState(false)return (<div><button onClick={() => setShow(true)}>Show</button>{show ? <input /> : null}</div>)}
Presumably after the user clicks “show” they will want to type something in the input there. Good focus management would focus the input after it becomes visible.
It’s important for you to know that in React state updates happen in batches. So state updates do not necessarily take place at the same time you call the state updater function.
As a result of React state update batching, if you try to focus an element right after a state update, it might not work as expected. This is because the element you want to focus on might not be available yet.
function MyComponent() {const inputRef = useRef<HTMLInputElement>(null)const [show, setShow] = useState(false)return (<div><buttononClick={() => {setShow(true)inputRef.current?.focus() // This probably won't work}}>Show</button>{show ? <input ref={inputRef} /> : null}</div>)}
The solution to this problem is to force React to run the state and DOM updates synchronously so that the element you want to focus on is available when you try to focus it.
You do this by using the flushSync
function from the react-dom
package.
import { flushSync } from 'react-dom'function MyComponent() {const inputRef = useRef<HTMLInputElement>(null)const [show, setShow] = useState(false)return (<div><buttononClick={() => {flushSync(() => {setShow(true)})inputRef.current?.focus()}}>Show</button>{show ? <input ref={inputRef} /> : null}</div>)}
What flushSync
does is that it forces React to run the state update and DOM
update synchronously. This way, the input element will be available when you try
to focus it on the line following the flushSync
call.
In general you want to avoid this de-optimization, but in some cases (like focus management), it’s the perfect solution.
Learn more in 📜 the flushSync
docs.
🧝♂️ I’ve put together a new component we need. It’s called <EditableText />
and
it allows users to edit a piece of text inline. We display it in a button and
when the user clicks it, the button turns into a text input. When the user
presses enter, blurs, or hits escape, the text input turns back into a button.
Right now, when the user clicks the button, the button goes away and is replaced
by the text input, but because their focus was on the button which is now gone,
their focus returns to the <body>
and the text input is not focused. This is
not a good user experience.
👨💼 Thanks Kellie. So now what we need is for you to properly manage focus for all of these cases.
Additionally, when the user clicks the button, we want to select all the text so it’s easy for them to edit.
🧝♂️ I’ve added some buttons before and after the input so you have something to test tab focus with. Good luck!
import { useRef, useState } from 'react'import { flushSync } from 'react-dom'import * as ReactDOM from 'react-dom/client'function EditableText({id,initialValue = '',fieldName,inputLabel,buttonLabel,}: {id?: stringinitialValue?: stringfieldName: stringinputLabel: stringbuttonLabel: string}) {const [edit, setEdit] = useState(false)const [value, setValue] = useState(initialValue)const inputRef = useRef<HTMLInputElement>(null)const buttonRef = useRef<HTMLButtonElement>(null)return edit ? (<formmethod="post"onSubmit={(event) => {event.preventDefault()flushSync(() => {setValue(inputRef.current?.value ?? '')setEdit(false)})buttonRef.current?.focus()}}><inputrequiredref={inputRef}type="text"id={id}aria-label={inputLabel}name={fieldName}defaultValue={value}onKeyDown={(event) => {if (event.key === 'Escape') {flushSync(() => {setEdit(false)})buttonRef.current?.focus()}}}onBlur={(event) => {flushSync(() => {setValue(event.currentTarget.value)setEdit(false)})buttonRef.current?.focus()}}/></form>) : (<buttonaria-label={buttonLabel}ref={buttonRef}type="button"onClick={() => {flushSync(() => {setEdit(true)})inputRef.current?.select()}}>{value || 'Edit'}</button>)}function App() {return (<main><button>Focus before</button><div className="editable-text"><EditableTextinitialValue="Unnamed"fieldName="name"inputLabel="Edit project name"buttonLabel="Edit project name"/></div><button>Focus after</button></main>)}const rootEl = document.createElement('div')document.body.append(rootEl)ReactDOM.createRoot(rootEl).render(<App />)
main {display: flex;flex-direction: column;gap: 1rem;padding: 3rem;}.editable-text {button {/* remove button styles. Make it look like text */background: none;border: none;padding: 4px 8px;font-size: 1.5rem;font-weight: bold;}input {/* make it the same size as the button */font-size: 1.5rem;font-weight: bold;padding: 4px 8px;border: none;}}
Quick Links
Legal Stuff
Social Media