2

I am new to Tradingview charting library and I want to create like responsive chart.

The problem is, trading view charting library requires to specify width and height. Here is the code.

const chart = LightweightCharts.createChart(e, {
      width: e.offsetWidth,
      height: e.offsetHeight,
      layout: {
        backgroundColor: 'rgb(17, 17, 39)',
        textColor: 'rgba(255, 255, 255, 0.9)',
      },
      grid: {
        vertLines: {
          color: 'rgb(41, 44, 58)',
        },
        horzLines: {
          color: 'rgb(41, 44, 58)',
        },
      },
      crosshair: {
        mode: LightweightCharts.CrosshairMode.Normal,
      },
      priceScale: {
        borderColor: 'rgba(197, 203, 206, 0.8)',
      },
      timeScale: {
        borderColor: 'rgba(197, 203, 206, 0.8)',
      },
    });
timocov
  • 980
  • 4
  • 15
dkregen
  • 380
  • 1
  • 6
  • 14

2 Answers2

4

This is the code from timocov's comment, which just work. Put it after createChart and setData. and rename chartContainer to your chart container HTML element.

  // Make Chart Responsive with screen resize
  new ResizeObserver(entries => {
      if (entries.length === 0 || entries[0].target !== chartContainer) { return; }
      const newRect = entries[0].contentRect;
      chart.applyOptions({ height: newRect.height, width: newRect.width });
    }).observe(chartContainer);
Ken Ratanachai S.
  • 2,927
  • 31
  • 40
1

You need to detect a resize event on the container element containing the chart, then update the charts dimensions with chart.applyOptions({ width: newWidth, height: newHeight })

There are some libraries to detect element resizes, the best non-lib way that I can find is with the ResizeObserver API, but it looks like it might not be integrated into all modern browsers yet. You would set an update callback function using the elements new height/width and use that in the ResizeObserver:

function resize() {
    chart.applyOptions({ width: $('#chartDiv').width(), height: $('#chartDiv').height() })
}

new ResizeObserver(outputsize).observe($('#chartDiv'))
Nick Friskel
  • 2,071
  • 2
  • 19
  • 31
  • 9
    You don't even need to measure container's height if you're using ResizeObserver: ``` new ResizeObserver(entries => { if (entries.length === 0 || entries[0].target !== container) { return; } const newRect = entries[0].contentRect; chart.applyOptions({ height: newRect.height, width: newRect.width }); }).observe(container); ``` – timocov Apr 28 '20 at 19:15