@shauny/chart-react
v0.1.1
Published
React bindings for @shauny/chart
Readme
@shauny/chart-react
React bindings for @shauny/chart. Provides a <CandleChart> component and a useChart hook for integrating the chart engine into React applications.
Installation
npm install @shauny/chart-react @shauny/chartPeer dependencies: react >= 18, @shauny/chart >= 0.1.0
<CandleChart>
import { CandleChart } from '@shauny/chart-react'
import type { Candle } from '@shauny/chart-react'
function App() {
const candles: Candle[] = [ /* ... */ ]
return (
<CandleChart
data={candles}
options={{ background: '#131722' }}
style={{ width: '100%', height: 500 }}
/>
)
}data is re-applied whenever the prop changes. On first mount fitToData() runs automatically; subsequent updates preserve the current zoom and pan position.
Props
| Prop | Type | Description |
|------|------|-------------|
| data | Candle[] | OHLCV array, sorted by time ascending |
| options | ChartOptions | Chart constructor options |
| style | CSSProperties | Inline style applied to the canvas |
| className | string | Class name applied to the canvas |
Imperative API via ref
import { useRef } from 'react'
import { CandleChart } from '@shauny/chart-react'
import type { CandleChartHandle } from '@shauny/chart-react'
function App() {
const chartRef = useRef<CandleChartHandle>(null)
return (
<>
<button onClick={() => chartRef.current?.fitToData()}>Fit All</button>
<CandleChart ref={chartRef} data={candles} style={{ width: '100%', height: 500 }} />
</>
)
}CandleChartHandle exposes:
fitToData()— reset viewport to show all datagetChart()— access the underlyingChartinstance (e.g. to add custom layers)
Real-time Updates
const [candles, setCandles] = useState<Candle[]>(initialCandles)
useEffect(() => {
const id = setInterval(() => {
setCandles(prev => {
const updated = [...prev]
const last = { ...updated[updated.length - 1] }
last.close = last.close + (Math.random() - 0.5) * 10
last.high = Math.max(last.high, last.close)
last.low = Math.min(last.low, last.close)
updated[updated.length - 1] = last
return updated
})
}, 500)
return () => clearInterval(id)
}, [])
return <CandleChart data={candles} style={{ width: '100%', height: 500 }} />useChart (Advanced)
Use this hook when you need direct access to the Chart instance — for example to add custom layers.
import { useEffect } from 'react'
import { useChart } from '@shauny/chart-react'
function CustomChart({ data }: { data: Candle[] }) {
const { ref, chartRef } = useChart({ background: '#131722' })
useEffect(() => {
const chart = chartRef.current
if (!chart) return
chart.addLayer(new ClosePriceLineLayer(data))
}, [])
useEffect(() => {
chartRef.current?.setData(data, true)
}, [data])
return <canvas ref={ref} style={{ width: '100%', height: 500 }} />
}License
MIT
