0

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 />
    );
  }
}

1 Answer 1

1

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";   
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.