I am trying to wrap an external library, that returns an HTMLElement object, in a React component.

Right now, I am simply defining a ref and appending the object like this:

class MyComponent extends React.Component {
  constructor(props) {
    super(props)
    this.externalLibrary = new ExternalLibrary()
  }
  componentDidMount() {
    this.externalLibrary()
      .then(contents => this.div.appendChild(contents))
  }
  render() {
    <div ref={div => this.div = div} />
  }
}

But AFAIU that means that that part of the DOM will not be managed by React. What would be the proper way to add the HTMLElement?

you need to use dangerouslySetInnerHTML

  componentDidMount() {
    let self= this;
    this.externalLibrary()
      .then(contents => self.setState({contents}))
  }
  render() {
    <div dangerouslySetInnerHTML={{__html: this.state.contents}} />
      }
4 users liked answer #0dislike answer #04
Fadi Abo Msalam profile pic
Fadi Abo Msalam

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).