PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, April 15, 2022

[FIXED] How to insert iframe created using js in a React component

 April 15, 2022     html, iframe, javascript, react-router, reactjs     No comments   

Issue

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.


Solution

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()



Answered By - Eliftch
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing