fixed height issue
This commit is contained in:
parent
5ecdf7c17c
commit
a29e6671bd
|
|
@ -1,13 +1,21 @@
|
||||||
'use client';
|
'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);
|
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!containerRef.current) return;
|
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");
|
const script = document.createElement("script");
|
||||||
script.src = scriptUrl;
|
script.src = scriptUrl;
|
||||||
|
|
@ -15,15 +23,13 @@ const useTradingViewWidget = (scriptUrl: string, config: Record<string, unknown>
|
||||||
script.innerHTML = JSON.stringify(config);
|
script.innerHTML = JSON.stringify(config);
|
||||||
|
|
||||||
containerRef.current.appendChild(script);
|
containerRef.current.appendChild(script);
|
||||||
containerRef.current.dataset.loaded = 'true';
|
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
if (containerRef.current) {
|
if (containerRef.current) {
|
||||||
containerRef.current.innerHTML = '';
|
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;
|
return containerRef;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue