How to get a React component's innerHTML

Viewed 29564

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

5 Answers

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>
}

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)

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)}}
        >;
}
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;
Related