The most effective way to set focus on any DOM element in React is by using the ref
attribute and accessing the focus()
method through a callback function.
Here is an easy example to understand.
Let’s say we want to set focus to an input field
return (
<>
<input type="text"/>
</>
)
Setting up the ref property
return (
<>
<input type="text" ref={inputref}/>
</>
)
Define the function
const inputref = (event) => { // this function is used to set the focus on the input element.
if (event) { // just a simple check to make sure even is not empty
event.focus(); //calling this function instantly set the focus to the DOM element
}
}
Using this method to set the focus is very useful when you want to set the focus on the element only under specific conditions or through your custom logic.
Hey, if you have any other doubts, feel free to ask in the comment section below.