Search code examples
javascriptreactjsweb

Loading javascript tag into react component


I'm trying to load a Trading View Widget inside a react component. I tried using _dangerouslySetInnerHTML, however, it doesn't run the javascript code.

I also tried this:

import React from 'react';

export default class TradingView extends React.Component{

  constructor(props){
    super(props);
  }

  componentDidMount() {
    const tradingViewCode = '<!-- TradingView Widget BEGIN --><script type="text/javascript" src="https://d33t3vvu2t2yu5.cloudfront.net/tv.js"></script><script type="text/javascript">new TradingView.widget({"autosize": true,"symbol": "BITFINEX:BTCUSD","interval": "D","timezone": "America/New_York","theme": "White","style": "1","locale": "en","toolbar_bg": "#f1f3f6","enable_publishing": false,"hide_top_toolbar": true,"save_image": false,"hideideas": true});</script><!-- TradingView Widget END -->';
    new Function(tradingViewCode)();
  }

  render(){
    return (
      <noscript />
    );
  }
}

Solution

  • One way could be to create & append those script elements to your <head> in componentDidMount like this:

    componentDidMount() {
        var headElem = document.getElementsByTagName('head')[0];
    
        var tradingWidgetSource = document.createElement('script');
        tradingWidgetSource.type = "text/javascript";
        headElem.appendChild(tradingWidgetSource);
        tradingWidgetSource.onload = function(){
            // Do your init logic here instead of the <script> tag.
            new TradingView.widget({"autosize": true,"symbol": "BITFINEX:BTCUSD","interval": "D","timezone": "America/New_York","theme": "White","style": "1","locale": "en","toolbar_bg": "#f1f3f6","enable_publishing": false,"hide_top_toolbar": true,"save_image": false,"hideideas": true});
        }
        tradingWidgetSource.src = "https://d33t3vvu2t2yu5.cloudfront.net/tv.js";   
    }