Design Converter
Education
Last updated on Feb 26, 2025
•4 mins read
Last updated on Feb 26, 2025
•4 mins read
Software Development Executive - I
Builds things that work. And if it doesn’t, he’ll fix it — with Neovim, of course.
Need to set focus on a div in your React app?
Managing focus helps users navigate smoothly, especially in forms, modals, and dynamic content. Without proper focus, interactions can feel clunky or confusing.
React provides several ways to control focus, making your interface more accessible and user-friendly.
Let’s look at simple techniques using hooks and lifecycle methods to manage focus the right way.
To understand the focus management process in React, consider the following diagram. It outlines how a component mounts, references are created, and focus is set on a desired element:
This diagram demonstrates the lifecycle: once the component mounts, the useRef
hook is used to capture a reference to the div. By setting tabIndex="-1"
, the div becomes focusable, and the useEffect
hook triggers the focus()
method to give the div focus.
Focus is a vital aspect of user interaction in web applications. It directs the user's attention, guiding them to the next expected input field or interactive area. In React, focus management is often achieved through:
• useRef
Hook: Creating a mutable reference to a DOM element.
• useEffect
Hook: Triggering actions when the component mounts.
• autofocus
Attribute: Automatically focusing the first focusable element upon render.
This ensures that elements such as input fields, buttons, or even divs can be programmatically focused, thereby enhancing the overall browsing experience.
To effectively set focus on an element like a div, follow these steps:
Create a Reference: Use the useRef
hook to create a reference.
Attach the Reference: Assign the reference to the element using the ref
attribute.
Make the Element Focusable: For non-interactive elements like <div>
, include tabIndex="-1"
.
Trigger Focus: Use the focus()
method inside the useEffect
hook to set the focus when the component mounts.
Here’s a concise example:
1import React, { useRef, useEffect } from 'react'; 2 3function FocusableDiv() { 4 const divRef = useRef(null); 5 6 useEffect(() => { 7 if (divRef.current) { 8 divRef.current.focus(); 9 } 10 }, []); 11 12 return ( 13 <div ref={divRef} tabIndex="-1" style={{ padding: '20px', border: '1px solid #ccc' }}> 14 This is a focusable div. 15 </div> 16 ); 17} 18 19export default FocusableDiv;
In this snippet:
• useRef
creates a reference (divRef
).
• tabIndex="-1"
makes the div focusable.
• useEffect
ensures the focus is applied after the component mounts.
For more complex applications, advanced focus techniques can be employed:
• Dynamic Focus Management: Update focus based on user actions or changes in state.
• Conditional Focusing: Use conditional logic inside useEffect
to focus different elements based on certain criteria.
• Custom Hooks for Focus: Create custom hooks (e.g., useInitialFocus
) that encapsulate focus logic, making your components cleaner and more modular.
Example of a custom hook for initial focus:
1import { useEffect } from 'react'; 2 3function useInitialFocus(ref) { 4 useEffect(() => { 5 if (ref.current) { 6 ref.current.focus(); 7 } 8 }, [ref]); 9} 10 11export default useInitialFocus;
And its implementation in a component:
1import React, { useRef } from 'react'; 2import useInitialFocus from './useInitialFocus'; 3 4function FocusableInput() { 5 const inputRef = useRef(null); 6 useInitialFocus(inputRef); 7 8 return ( 9 <input ref={inputRef} placeholder="Focus on me automatically" /> 10 ); 11} 12 13export default FocusableInput;
This custom hook simplifies reusing focus logic across multiple components.
To integrate focus management in your application:
• Identify Focusable Elements: Determine which elements need to be focused, such as input fields, buttons, or even informational divs.
• Use Appropriate Hooks: Leverage useRef
and useEffect
for classless components or componentDidMount
in class components.
• Optimize User Experience: Ensure focus transitions are smooth and logical. Avoid overusing focus shifts, which may confuse users.
For example, you can add the autoFocus
attribute to the first input field in a form:
1function LoginForm() { 2 return ( 3 <form> 4 <input autoFocus placeholder="Username" /> 5 <input placeholder="Password" type="password" /> 6 <button type="submit">Login</button> 7 </form> 8 ); 9} 10 11export default LoginForm;
Alternatively, for a more dynamic approach:
1import React, { useRef, useEffect } from 'react'; 2 3function DynamicFocusComponent({ isActive }) { 4 const elementRef = useRef(null); 5 6 useEffect(() => { 7 if (isActive && elementRef.current) { 8 elementRef.current.focus(); 9 } 10 }, [isActive]); 11 12 return ( 13 <div ref={elementRef} tabIndex="-1"> 14 {isActive ? "I'm active and focused!" : "I'm not focused."} 15 </div> 16 ); 17} 18 19export default DynamicFocusComponent;
This example demonstrates conditional focusing based on a prop (isActive
), making your component more interactive and context-aware.
React makes it easy to manage focus, but thoughtful implementation improves the user experience. Using useRef
, useEffect
, and tabIndex
helps control focus smoothly. When you need to set focus on a div, these methods ensure accessibility and better navigation. Try different approaches to find what works best for your project.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.