Given a HTMLElement
ref created by React.useRef()
, is it possible to render a new Component inside of it?
For example:
const DemoComponent: React.FunctionComponent = () => {
const ref = React.useRef<HTMLElement>(null);
useRenderExample(ref);
return (
<>
<div ref={ref}>RENDER_PLACEHOLDER</div>
<div>Some other elements and components...</div>
</>
);
}
function useRenderExample(ref: React.RefObject<HTMLElement>) {
const element = ref.corrent;
if (element) {
// 1. This will work:
element.innerHTML = 'Hello World';
// 2. This will NOT work (innerHTML except string only):
// h1 is just an example, I would like to have here
// a more complex FunctionComponent
element.innerHTML = <h1>HELLO</h1>;
}
}
2
Answers
After some investigation I found the ReactDOM package - that you are probably already using for rendering your entire application (unless you are using different render engine like ReactNative, ReactVR, etc...).
The ReactDOM come with a few render methods, the one I found useful is
ReactDOM.render(componentToRender, containerElement);
To solve my issue I used:
You should also look at
ReactDOM.createPortal(..)
(thank to Ori Drori for his answer) that has a similar API parameters. Allows you to render in a different part of the DOM, recommended for popups and tooltips.(However in my case, no matter how much I tried - I could not make it work)
*As a side node - the HTMLElement could be any element reference, and not only one created with
useRef
. You can also usedocument.getElementById
(or other element selector method) or create a new element withdocument.createElement
or withReact.createElement
.Use a portal to render a React element inside a DOM node:
Example: