Hi I am new to react and on my page load i need to give focus to a button. I am using functional component. I had seen example with class component and in that using componentDidMount and setting focus using refs.
Here i am using functional component and no ComponentDidMount as well.. How can i set focus on functional component to a button on page load ?
export const SubPageHeader=({prop})=>{
return(
<div>
<input type="button"/>
}
export default SubPageHeader
By setting the focus on an element, we gently guide a user to the next expected input field, giving them a better browsing experience with less guesswork. In this article, we will learn how to set focus on an element after rendering our React application or a React component.
To set focus in React, we can use Refs to DOM elements. Sometimes a parent component needs to set focus to an element in a child component. We can do this by exposing DOM refs to parent components through a special prop on the child component that forwards the parent's ref to the child's DOM node.
In react, we have the ComponentDidMount() lifecycle method where it runs when a component is mounted to the dom tree. The ComponentDidMount() method is the best place to set a focus on the input element.
You can make use of useEffect
hook which is equivalent to componentDidMount
,
const SubPageHeader=({prop})=>{
let textInput = null;
useEffect(()=>{
textInput.focus();
})
return(
<div>
<input type="button" value="Button" ref={(button) => { textInput = button; }}/>
</div>
)
}
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With