midhun k
midhun k

Reputation: 576

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

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

Upvotes: 7

Views: 15953

Answers (3)

ravibagul91
ravibagul91

Reputation: 20755

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

Upvotes: 18

Bhawana
Bhawana

Reputation: 380

For function component you can use hooks, You can use useEffect it is work as ComponentDidMount for functional component.For more detail go through this link : https://reactjs.org/docs/hooks-state.html

Upvotes: -1

niks
niks

Reputation: 466

you can use useEffect instead of componentDidMount to do same thing in functional component.

Use ref on your button element and use it in useEffect method of react to focus button element

Upvotes: 0

Related Questions