Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs: Callback for dangerouslySetInnerHTML complete

Tags:

reactjs

I'm currently having a React Component like this:

        <div id="product-content" className="bz">
            <a className="anchor" id="content-anchor"></a>
            <h2 className="title-section">Thông tin sản phẩm</h2>
            <div className="fixed-menu-content">
                <div className="container">
                    <ul>
                        <li><a href="#content-anchor">Thông tin sản phẩm</a></li>
                        <li><a href="javascript:void(0)">Video sản phẩm</a></li>
                        <li><a href="#rating-anchor">Đánh giá (19)</a></li>
                        <li><a href="#guide-anchor">Hướng dẫn mua hàng</a></li>
                    </ul>
                </div>
            </div>
            <div dangerouslySetInnerHTML={{__html: description}}></div>
        </div>

It seems that dangerouslySetInnerHTML doesn't impact to Component Lifecycle. I put this line in componentDidMount, but it return wrong result:

let b = $("#product-content").height(); // wrong: 600, true: 6500

If I try to run above line in console dev tool, it returns true result because component has been rendered completely.

How can I trigger callback for dangerouslySetInnerHTML?

like image 862
Viet Phan Avatar asked Dec 23 '22 17:12

Viet Phan


1 Answers

It looks like the DOMSubtreeModified event has been deprecated in favor of the Mutation Observer API.

You could refactor the code proposed by lustoykov to use the new API:

class ContentRenderer extends React.Component {
  componentDidMount() {
      this.observer = new MutationObserver(this.handleMutation);
      this.observer.observe(this.myElement, {
        // Check config in https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
        childList: true,
        attributes: true,
        characterData: true
      });
    }
  
    componentWillUnmount() { 
      this.observer.disconnect();
    }
    
    handleMutation() {
      console.log('mutation');
    }
    
    render() {
      return (
        <div 
          dangerouslySetInnerHTML={{ __html: "<div>Test</div>" }}
          ref={(myElement) => { this.myElement = myElement; }}
        />
      );
    }
  }
like image 183
Ariel Gerstein Avatar answered Dec 31 '22 02:12

Ariel Gerstein