Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to add HTMLElement?

Tags:

reactjs

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?

like image 521
spbks Avatar asked Mar 15 '18 10:03

spbks


People also ask

How do you add data attribute in React?

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!


1 Answers

you need to use dangerouslySetInnerHTML

  componentDidMount() {
    let self= this;
    this.externalLibrary()
      .then(contents => self.setState({contents}))
  }
  render() {
    <div dangerouslySetInnerHTML={{__html: this.state.contents}} />
      }
like image 78
Fadi Abo Msalam Avatar answered Sep 21 '22 18:09

Fadi Abo Msalam