Skip to content
Advertisement

Passing HTML element into React Component before Element is Rendered

If we have the React component Foo that instantiates the class Bar and we need to pass the HTMLCollection element with ID foo into Bar, how can it be done?

Bar.js should ideally remained unchanged.

I tried the following:

Foo.js

JavaScript

Bar.js

JavaScript

but domElement is always null, maybe because when we run document.getElementById, the element div#foo has not been rendered yet.


Also tried the using useRef:

Foo.js

JavaScript

Bar.js

JavaScript

but getting the error

Uncaught TypeError: domElement.getElementsByClassName is not a function

What is the correct way to do this?

Advertisement

Answer

You can use useLayoutEffect hook which fires synchronously after all DOM mutations

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement