I am trying to build an app with an iframe. It will have controllers to change the iframe style and add text to it. Iframe will be like a preview. I want to create the iframe with javascript. I tried this to create the element and append it to component return div like this:
let iframe = document.createElement('iframe');
document.querySelector('#iframeContainer').appendChild(iframe);
ı received this error :TypeError: Cannot read properties of null (reading 'appendChild')
I also tried another method :
let iframe = React.createElement('iframe', {});
ReactDOM.render(
iframe, document.getElementById('root')
);
in this method, because I don't have a return value, it throws an error. I am not able to insert it in a component.
How should I tackle this problem? I am open to all ideas.
I found a solution to this problem. While I was trying to append the element, I missed out on the component lifecycle. After spending good amount of time here is my solution :
const createIframe = () => {
const iframe = document.createElement('iframe');
document.getElementById('iframeContainer').appendChild(iframe);
}
useEffect(() => {
createIframe();
});
By calling my function in useEffect I made sure that div I wanted to append chil is created. I used useEffect but if you're using class component you should use componenDidMount()