简体   繁体   中英

Why can't I access children of a element rendered through React DOM?

I am trying to access the children of the measureDiv I created and appended with ReactDOM.create in the folllowing snippet, I am calling this function in a hook only on mount of the element. The problem is that the element's children are empty although it is rendered on the screen and visible in the inspector. I am able to access the children on the second render.

const containerRef = useRef<ReactNode | null>(null)

const measureElement = (element:any, layerId = "root") => {
  const measureLayer = document.createElement("div");
  measureLayer.setAttribute("class", "measure-div");
  measureLayer.setAttribute("id", "measure-div");

  ReactDOM.render(element, measureLayer);

  containerRef.current?.appendChild(measureLayer);

  const measureDiv = document.getElementById("measure-div");

  console.log(measureDiv, measureDiv.children.item(0))
}

useEffect(() => {
  measureElement(
    <BrowserRouter>
      <MuiThemeProvider theme={ManagementTheme}>
        <Element {...{props}/>
      </MuiThemeProvider>
    </BrowserRouter>
  )
}, [])

return (
  <Grid
      container
      className={classes.columnContainer}
      data-automation-id="test-answers-row"
      id="test-answers-row"
      ref={containerRef}
  />
)

My question is why can't I access the children that I render in a Node through ReactDOM.render right after I render them? And why I get them on the next render?

Incase you are wondering I am trying to render the element in a hidden div before rendering to the App to get its size to predict the layout.

From React docs :

ReactDOM.render() currently returns a reference to the root ReactComponent instance. However, using this return value is legacy and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root ReactComponent instance, the preferred solution is to attach a callback ref to the root element.

You can check it by delaying reading childs of root (measureLayer) element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM