9

I have a react component and I want its innerHTML to pass as prop to an iframe.

render() {
        const page = <PrintPage />
        const iframeContent = page..something...innerHTML
        return (
            <iframe srcDoc={iframeContent}/>);
}

Is there any way for doing like this.

I want to render only within the iframe, so i can't use ref. I want the innerHTML of component which is not mounted

PranavPinarayi
  • 3,037
  • 5
  • 21
  • 32
  • Possible duplicate of [How to access a DOM element in React? What is the equilvalent of document.getElementById() in React](https://stackoverflow.com/questions/38093760/how-to-access-a-dom-element-in-react-what-is-the-equilvalent-of-document-getele) – Shubham Khatri Aug 02 '17 at 09:38

5 Answers5

11

You can use refs or ReactDOM.findDOMNode to get innerHTML but the component should be mounted.

class App extends React.Component{

  componentDidMount(){
    console.log(this.ref.innerHTML)
    console.log(ReactDOM.findDOMNode(this).innerHTML)
  }
  render(){
    return (
      <div ref={r=>this.ref = r}>app</div>
    )
  }
}

ReactDOM.render(
  <App />,document.getElementById("app")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
1

Here is how you can do it with useRef() BEFORE the component is mounted:

use useEffect hook (don't pass any other parameter to useEffect so that it runs after every render)

(NOTE: in this approach, you can't change the return value of component - except if you access it with ref.current or document):

function Component(){
const ref = useRef(null);
useEffect(()=>{
    //you can access ref here because useEffect runs after rendering
    })
return <div ref={ref}></div>
}
0

Maybe a bit late for a reply, but you may try reaching the react children elements through ref:

const r = React.useRef(null);
console.log(r.current.children)
Julio Pereira
  • 70
  • 1
  • 7
0
import { useEffect, useRef } from "react";

const App = () => {
  const Ref = useRef(this);

  useEffect(() => {
    let cache = "";
    for (let i = 1800; i < 2022; i++) {
      cache += `<option>${i}</option>`;
    }
    Ref.current.innerHTML = cache;
  });

  return (
      <select ref={Ref}></select>
  );
};

export default App;
-2

You can access the innerHTML like this:

render() {
 const page = <PrintPage />
 const iframeContent = (e) =>{console.log(e.target.innerHTML)}

 return <iframe 
           srcDoc={iframeContent}
           onClick={(e)=>{handleClick(e)}}
        >;
}
Irvin Sandoval
  • 742
  • 7
  • 18
Aditi Singh
  • 34
  • 2
  • 6