Jun
Jun

Reputation: 33

TradingVew chart in React, code is not working

I try to change this code for react, but not working, ReferenceError: TradingView is not defined

In vanilla html, It working, but react code is not working How can I do ?

<div class="tradingview-widget-container">
      <div id="tradingview_7bf97"></div>

      <script
        type="text/javascript"
        src="https://s3.tradingview.com/tv.js"
      ></script>
      <script type="text/javascript">
        new TradingView.widget({
          autosize: true,
          symbol: "NASDAQ:AAPL",
          interval: "D",
          timezone: "Etc/UTC",
          theme: "light",
          style: "1",
          locale: "kr",
          toolbar_bg: "#f1f3f6",
          enable_publishing: false,
          allow_symbol_change: true,
          container_id: "tradingview_7bf97"
        });
      </script>
    </div>

react code I use ref, and script async, I think async can download javascript code first, at new Trading View code, browser can find TradingView.widget, but can not find

import React, { Component } from 'react';
import styles from './TradeChart.scss';
import className from 'classnames/bind';

const cx = className.bind(styles);

class TradeChart extends Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  componentDidMount() {
    const scriptSrc = document.createElement('script');
    const script = document.createElement('script');
    scriptSrc.src = 'https://s3.tradingview.com/tv.js';
    scriptSrc.async = true;

    script.innerHTML = `new TradingView.widget(
      {
      "autosize": true,
      "symbol": "NASDAQ:AAPL",
      "interval": "D",
      "timezone": "Etc/UTC",
      "theme": "light",
      "style": "1",
      "locale": "kr",
      "toolbar_bg": "#f1f3f6",
      "enable_publishing": false,
      "allow_symbol_change": true,
      "container_id": "tradingview_7bf97"
    }
      );`;
    this.myRef.current.appendChild(scriptSrc);
    this.myRef.current.appendChild(script);
  }
  render() {
    return (
      <div className="tradingview-widget-container" ref={this.myRef}>
        <div id="tradingview_7bf97"></div>
      </div>
    );
  }
}

export default TradeChart;

Upvotes: 2

Views: 2793

Answers (1)

Coel Drysdale
Coel Drysdale

Reputation: 223

This is how I implemented it. Hopefully it works for you too.

I added the script to the end of the body of the html file

<body>
...
<script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>
</body>

And in the component i added new window.TradingView.widget({})

script.innerHTML = new window.TradingView.widget({...config...})

Upvotes: 2

Related Questions