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?
To set a data attribute on an element in React, set the attribute directly on the element, e.g. <button data-test-id="my-btn"> or use the setAttribute() method, e.g. el. setAttribute('data-foo', 'bar') . You can access the element on the event object or using a ref . Copied!
you need to use dangerouslySetInnerHTML
  componentDidMount() {
    let self= this;
    this.externalLibrary()
      .then(contents => self.setState({contents}))
  }
  render() {
    <div dangerouslySetInnerHTML={{__html: this.state.contents}} />
      }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With