import { useRootColors } from '@cerberus/react'
This hook allows you to access Cerberus colors from the document root which is useful when you want to use Cerberus colors within a canvas
element.
Usage
This is adding data-viz colors to a canvas element.
Advanced Usage
If you need to get the latest colors when a user changes the color mode or theme, you can use the refetch
function to get the latest colors from the document root.
'use client'
import { useRootColors, useTheme } from '@cerberus/react'import { useEffect, useState } from 'react'
const initialSettings = {...stuffFromXChartLibrary}
const colorList = [ 'dataViz.diverging.50', 'dataViz.diverging.100', 'dataViz.diverging.200',]
function SomeChart() { const [settings, setOptions] = useState(initialSettings)
const { theme } = useTheme() const { colors, refetch } = useRootColors(colorList)
useEffect(() => { if (window && theme) { // We need to wait for the theme to be applied to the root element setTimeout(async () => { await refetch() }, 10) } }, [theme, refetch])
useEffect(() => { const start = colors[colorList[0]] setOptions((prev) => ({ ...prev, background: { image: `radial-gradient(75% 82% at 52% 100%, ${start}40 0%, transparent 100%)`, }, })) }, [colors])
return ( <SomeChartLib settings={settings} /> )}
API
export interface RootColorsResult { colors: Record<string, string> refetch: () => void}
define function useRootColors(colors: string[] = []): RootColorsResult
Arguments
The useRootColors
hook accepts the following optional arguments:
Name | Default | Description |
---|---|---|
colors | An array of Cerberus color keys to retrieve. | |
refetch | A function to refetch the colors from the root. |
Return
The useRootColors
hook returns a memoized object with the same properties as the options object passed in.
{ colors: { 'dataViz.diverging.50': '#F7F7F7', 'dataViz.diverging.100': '#E5E5E5', 'dataViz.diverging.200': '#C6C6C6', }, refetch: () => void}