0

When React updated dom in browser?

Reproduction


The first time

render methods, in this time, document.getElementById show null


The second time updated,

document.getElementById get new DOM

I expected it should get old DOM, but document.getElementById get new one.


In lifecycles diagram, it show ­React updates ­D­O­M after render, so I think

document.getElementById should take old dom.

T Ty
  • 190
  • 1
  • 7

2 Answers2

0

document.getElementById at first returns null because your are trying to get the element before rendering it thus it does not exist at the moment. The second time the component has mounted and thus an element with an id of #a exist and is returned.

If you want to get the previous state, you can use this:

this.setState((prevState, pros) => {
    // your code here.
});
Khalil
  • 1,495
  • 6
  • 14
  • This is not problem where focus, the problem is why it get new dom – T Ty Dec 26 '21 at 03:04
  • Are you looking for this? https://stackoverflow.com/questions/68892947/how-can-i-get-old-value-in-inputs-onchange-event – Khalil Dec 26 '21 at 03:10
  • I have described it. – T Ty Dec 26 '21 at 03:16
  • Okay so I did some research and it seems document API may or may not work as expected with React Framework, and it is recommended to use `refs` instead as they are more inline with the framework. I could not find the exact reason of this behavior of the document API. – Khalil Dec 26 '21 at 04:18
0

After render() method called, the render process occurs.

It means #a only created when you return <div>...</div>

Let's see your code

  render() {
    console.log("render");

    // => 1. you want to find #a but it not rendered yet
    // so result is undefined
    console.log(document.getElementById("a")); 


    // 2. #a rendered at this line, not above
    return (<div>....</div>); 
  }

Try to wait 100ms and print #a again

  render() {

    // 1. wait to 100ms
    setTimeout(() => {
      // => 3. now, you found #a, because after 100ms it rendered already
      console.log(document.getElementById("a"));   
    }, 100)

    // 2. #a rendered at this line
    return (<div>....</div>); 
  }
hudy9x
  • 134
  • 6