7

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

3 Answers 3

18

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

Sign up to request clarification or add additional context in comments.

7 Comments

I really love this demo but for me am getting Uncaught TypeError: Object(...) is not a function :(
any reason why coming like this @ravibagul91
You need to useState for the textInput value
@ravibagul91 , there's no need to use useRef ?
@ChrisHaines , there's no need to use useRef?
|
0

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

3 Comments

But for using refs we need to use stateful component
They can't have state, refs or lifecycle methods for stateless components @niks
you can see this page to get more info. reactjs.org/docs/refs-and-the-dom.html
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.