How does React handle focus management and accessibility?
React itself does not directly manage focus or accessibility, but provides tools to effectively deal with these issues. 1. Use Refs to programmatically manage focus, such as setting element focus through useRef; 2. Use ARIA attributes to improve accessibility, such as defining the structure and state of tab components; 3. Pay attention to keyboard navigation to ensure that the focus logic in components such as modal boxes is clear; 4. Try to use native HTML elements to reduce the workload and error risk of custom implementations; 5. React assists accessibility by controlling the DOM and adding ARIA attributes, but the correct use still depends on developers.
React itself doesn't directly manage focus or accessibility — that's more the job of the browser and developers. But React gives you tools to handle these things effectively, especially when building complex UIs like dropdowns, modals, or custom controls.

Here's how it works in practice:

Use Refs to Manage Focus Programmatically
If you want to set focus on an element — say, after a modal opens or an error occurs — you'll typically use a ref
.
const inputRef = useRef(null); useEffect(() => { inputRef.current.focus(); }, []);
This is common for form fields, alerts, or dynamically added elements. Just be careful not to overdo it — unexpected focus changes can confuse screen reader users.

ARIA Attributes Improve Accessibility
React supports all standard ARIA attributes, so you can make custom components accessible. For example, if you're building a tab component from scratch:
- Use
role="tablist"
,role="tab"
, androle="tabpanel"
to define structure. - Add
aria-selected
,aria-controls
, andaria-labelledby
to manage state and relationships.
These help screen readers understand your UI even when it's not built with native HTML elements like <select></select>
or <details></details>
.
Keyboard Navigation Is Critical
Focus management isn't just about setting focus — it's also about where focus goes next.
For example, when a modal opens:
- Move focus inside the modal (eg, to the close button or first input).
- Trap focus so it doesn't escape to the background content.
- Restore focus to the triggering element when the modal closes.
You can do this manually using tabIndex
, onKeyDown
, and refs — or use libraries like react-aria or Reach UI which handle this for you.
Don't Forget Native Elements
Whenever possible, use native HTML elements like <button></button>
, <input>
, or <a></a>
. They come with built-in keyboard and screen reader support. If you build a fake button with a <div> , you'll need to add:<ul>
<li> <code>role="button"
tabIndex="0"
to make it focusedonClick
and key events like Enter and SpaceThat's extra work — and easy to get wrong.
So yes, React helps with accessibility by letting you control the DOM and add ARIA attributes easily, but it's still up to you to use them correctly.
Basically that's it.
The above is the detailed content of How does React handle focus management and accessibility?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebAssembly(WASM)isagame-changerforfront-enddevelopersseekinghigh-performancewebapplications.1.WASMisabinaryinstructionformatthatrunsatnear-nativespeed,enablinglanguageslikeRust,C ,andGotoexecuteinthebrowser.2.ItcomplementsJavaScriptratherthanreplac

Server-siderendering(SSR)inNext.jsgeneratesHTMLontheserverforeachrequest,improvingperformanceandSEO.1.SSRisidealfordynamiccontentthatchangesfrequently,suchasuserdashboards.2.ItusesgetServerSidePropstofetchdataperrequestandpassittothecomponent.3.UseSS

Front-end applications should set security headers to improve security, including: 1. Configure basic security headers such as CSP to prevent XSS, X-Content-Type-Options to prevent MIME guessing, X-Frame-Options to prevent click hijacking, X-XSS-Protection to disable old filters, HSTS to force HTTPS; 2. CSP settings should avoid using unsafe-inline and unsafe-eval, use nonce or hash and enable reporting mode testing; 3. HTTPS-related headers include HSTS automatic upgrade request and Referrer-Policy to control Referer; 4. Other recommended headers such as Permis

The core of VR web front-end development lies in performance optimization and interactive design. You need to use WebXR to build a basic experience and check device support; choose A-Frame or Three.js framework development; uniformly process input logic of different devices; improve performance by reducing drawing calls, controlling model complexity, and avoiding frequent garbage collection; design UI and interactions that adapt to VR characteristics, such as gaze clicks, controller status recognition and reasonable layout of UI elements.

The core of front-end error monitoring and logging is to discover and locate problems as soon as possible, and avoid user complaints before knowing them. 1. Basic error capture requires the use of window.onerror and window.onunhandledrejection to catch JS exceptions and Promise errors; 2. When selecting the error reporting system, give priority to tools such as Sentry, LogRocket, Bugsnag, and pay attention to SourceMap support, user behavior tracking and grouping statistics functions; 3. The reported content should include browser information, page URL, error stack, user identity and network request failure information; 4. Control the log frequency to avoid log explosion through strategies such as deduplication, current limiting, and hierarchical reporting.

Event delegation is a technique that uses the event bubble mechanism to hand over the event processing of child elements to the parent element. It reduces memory consumption and supports dynamic content management by binding listeners on parent elements. The specific steps are: 1. Binding event listeners to the parent container; 2. Use event.target to determine the child elements that trigger the event in the callback function; 3. Execute the corresponding logic based on the child elements. Its advantages include improving performance, simplifying code maintenance and adapting to dynamically added elements. When using it, you should pay attention to event bubble restrictions, avoid excessive centralized monitoring, and reasonably select parent elements.

Common problems with dependency arrays when using useEffect include: 1. Not including all dependencies causes closure problems, and all variables used in effect should be added to the array; 2. Adding unstable dependencies to trigger an infinite loop, and useMemo or useCallback should be used to optimize or remove components; 3. Overuse use of useEffect to deal with derived state, and useMemo should be used instead; 4. Ignore the cleaning logic of asynchronous operations and cancel unfinished tasks in return. Correct handling of dependencies and side-effect behaviors can avoid most problems.

Common causes and response methods for front-end memory leaks: 1. The event listener is not properly cleaned, such as the useEffect in React does not return the unbinding function; 2. The closure reference causes the variable to be recycled, such as the external variables in setInterval are continuously referenced; 3. The third-party library is improperly used, such as the Vue watch is not properly cleaned. The detection method includes using ChromeDevTools' Performance and Memory panels to analyze memory trends and object releases. Best practices to avoid memory leaks include manually cleaning side effects when component unloading, avoiding references to large objects in closures, using WeakMap/WeakSet instead of ordinary collections, optimizing complex structural operations, and regular performance
