fixed height issue

This commit is contained in:
Mr. Algorithm
2026-02-01 04:39:21 +05:30
parent 5ecdf7c17c
commit a29e6671bd

View File

@@ -1,13 +1,21 @@
'use client';
import { useEffect, useRef } from "react";
import { useEffect, useRef } from "react";
const useTradingViewWidget = (scriptUrl: string, config: Record<string, unknown>, height = 600) => {
const useTradingViewWidget = (scriptUrl: string, config: Record<string, unknown>, height: number | string = 600) => {
const containerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
if (!containerRef.current) return;
if (containerRef.current.dataset.loaded) return;
containerRef.current.innerHTML = `<div class="tradingview-widget-container__widget" style="width: 100%; height: ${height}px;"></div>`;
// Clean up previous instance
containerRef.current.innerHTML = '';
// Create wrapper with dynamic height support
// If autosize is true in config, we want 100% height/width
const isAutosize = config.autosize === true;
const styleHeight = isAutosize ? '100%' : `${height}px`;
containerRef.current.innerHTML = `<div class="tradingview-widget-container__widget" style="width: 100%; height: ${styleHeight};"></div>`;
const script = document.createElement("script");
script.src = scriptUrl;
@@ -15,15 +23,13 @@ const useTradingViewWidget = (scriptUrl: string, config: Record<string, unknown>
script.innerHTML = JSON.stringify(config);
containerRef.current.appendChild(script);
containerRef.current.dataset.loaded = 'true';
return () => {
if(containerRef.current) {
if (containerRef.current) {
containerRef.current.innerHTML = '';
delete containerRef.current.dataset.loaded;
}
}
}, [scriptUrl, config, height])
}, [scriptUrl, JSON.stringify(config), height]) // Use stringified config to avoid ref issues
return containerRef;
}