Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react way of setting focus on a particular button in functional component?

Tags:

focus

reactjs

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
like image 499
midhun k Avatar asked Jul 25 '19 11:07

midhun k


People also ask

What is focus () in React?

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.

How do you manage focus in React?

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.

How do you focus on input element in React?

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.


1 Answers

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

like image 92
ravibagul91 Avatar answered Nov 15 '22 09:11

ravibagul91