I need to make sure an input element is focused when the following is true:

  • the DOM is available and
  • properties got changed

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();
    }

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()

39 users liked answer #0dislike answer #039
Murat Karagöz profile pic
Murat Karagöz

Each of your conditions require you to place the code inside 1 function each:

  • the DOM is available and - componentDidMount
  • properties got changed - componentDidUpdate

So you have to place inside both functions.
Another option is to call setState() inside componentDidMount, so that componentDidUpdate is invoked.

10 users liked answer #1dislike answer #110
Dane profile pic
Dane

componentDidMount()

componentDidMount() will be rendered immediately after a component is mounted. This method will render only once and all the initialization that requires DOM nodes should go here. Setting state in this method will trigger a re-rendering.

componentDidUpdate()

componentDidUpdate() is invoked immediately every time the updating occurs. This method is not called for the initial render.

You can understands more from this below example

import React from 'react';

class Example extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  componentDidMount() {

    //This function will call on initial rendering.
    document.title = `You clicked ${this.state.count} times`;

  }
  componentDidUpdate() {
     document.title = `You clicked ${this.state.count} times`;
   }

  render(){
    return(
      <div>
      <p>You clicked {this.state.count} times</p>
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Click me
      </button>
    </div>
    )
  }
}
export default Example;

You can understand by commenting and un-commenting both methods.

4 users liked answer #2dislike answer #24
Muhammad Usama Rabani profile pic
Muhammad Usama Rabani

componentDidUpdate is not called at initial render (see https://reactjs.org/docs/react-component.html#componentdidupdate) so you probably must call it twice as in your example.

3 users liked answer #3dislike answer #33
keul profile pic
keul

In React v16.7.0-alpha you can use the useEffect hook:

import React, { useEffect, useRef } from "react";

function InputField() {
  const inputRef = useRef();

  useEffect(() => {
    inputRef.current.focus();
  });

  return <input ref={inputRef} />;
}

From the docs:

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

Example

Note: as mentioned, this will not work with class based components.

2 users liked answer #4dislike answer #42
zok profile pic
zok

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).