Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a React component's innerHTML

Tags:

reactjs

iframe

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

like image 605
PranavPinarayi Avatar asked Aug 02 '17 09:08

PranavPinarayi


People also ask

How do I get inner text in react JS?

When the button element is clicked, the click event gets triggered, the value of the tagName property can be used to find out HTML element the source of the event and innerText property can be used to find out text written in that HTML element.

Can we use innerHTML in React?

This rule applies when innerHTML prop for a React DOM element is used. innerHTML prop is risky because it is easy to expose your users to a cross-site scripting (XSS) attack.

How do you get the DOM element in React?

In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.


1 Answers

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>
like image 199
Anurag Awasthi Avatar answered Oct 06 '22 13:10

Anurag Awasthi