I need to make sure an input element is focused when the following is true:
Question: Do I need to put my code in both componentDidUpdate
and componentDidMount
or just componentDidUpdate
would be suffice?
private makeSureInputElementFocused() { if (this.props.shouldGetInputElementFocused && this.inputElement !== null) { this.inputElement.focus(); } } componentDidMount() { this.makeSureInputElementFocused(); // <-- do i need this? } componentDidUpdate() { this.makeSureInputElementFocused(); }
The componentDidUpdate()is called after componentDidMount() and can be useful to perform some action when the state of the component changes. Parameters: Following are the parameter used in this function: prevProps: Previous props passed to the component. prevState: Previous state of the component.
componentDidUpdate provides the previous React props and state values, and useEffect doesn't. There are hacks to get previous props and state with useEffect , but it doesn't do that out of the box.
The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.
componentDidUpdate does not get called after the first initial render() lifecycle.
You have to use both.
componentDidMount()
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
componentDidUpdate()
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
You also could place it into the render()
method which seems like it's appropriate for your case since you always want to check the focus. Then you don't need to put it into componentDidMount()
and componentDidUpdate()
Each of your conditions require you to place the code inside 1 function each:
componentDidMount
componentDidUpdate
So you have to place inside both functions.
Another option is to call setState()
inside componentDidMount
, so that componentDidUpdate
is invoked.
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