'How to get a React component's innerHTML
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
Solution 1:[1]
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>
Solution 2:[2]
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)
Solution 3:[3]
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)}}
>;
}
Solution 4:[4]
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;
Solution 5:[5]
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>
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anurag Awasthi |
| Solution 2 | Julio Pereira |
| Solution 3 | Irvin Sandoval |
| Solution 4 | Wael Alhassan |
| Solution 5 |
