Skip to content

Docs: explain CUSTOM_SYMBOL_FN usage in SSR / Next.js (document is not defined) #115

@afucher

Description

@afucher

Context

Issue #87 asks how to use CUSTOM_SYMBOL_FN in Next.js. The existing Custom Symbols guide is thorough for browser environments, but it uses document.createElementNS(...) in all its examples.

In Next.js (and any other SSR framework), this call runs during server-side rendering where document is not defined, causing a ReferenceError: document is not defined crash.

What is missing from the docs

  1. An explicit SSR warning — note that CUSTOM_SYMBOL_FN (and the whole chart rendering) must run client-side only.
  2. A Next.js-specific pattern — show how to guard the chart initialisation so it only runs in the browser:
    • Using typeof window !== 'undefined' guards
    • Using a useEffect hook (the correct React pattern for DOM/SVG manipulation)
    • Using Next.js dynamic(() => import('./MyChart'), { ssr: false }) to load the chart component without SSR
  3. A note in the Frameworks guide — the existing guides/frameworks/ directory has pages for React, Angular, and Vue; these should each mention that Chart must be instantiated inside a lifecycle hook / after hydration, and that CUSTOM_SYMBOL_FN callbacks follow the same rule.

Example that should be added

// In Next.js — correct pattern (runs only in the browser)
import { useEffect, useRef } from 'react'
import { Chart } from '@astrodraw/astrochart'

export default function MyChart({ data }) {
  const ref = useRef(null)

  useEffect(() => {
    if (!ref.current) return
    const chart = new Chart(ref.current.id, 600, 600, {
      CUSTOM_SYMBOL_FN: (name, x, y) => {
        // document is safely available here — we are in the browser
        const el = document.createElementNS('http://www.w3.org/2000/svg', 'circle')
        el.setAttribute('cx', String(x))
        el.setAttribute('cy', String(y))
        el.setAttribute('r', '8')
        el.setAttribute('fill', '#FFD700')
        return el
      }
    })
    chart.radix(data)
  }, [data])

  return <div id="my-chart" ref={ref} />
}

Relevant links

  • Original question: I have a few questions. #87
  • Existing custom-symbols guide: website/src/content/docs/guides/custom-symbols.md
  • Existing frameworks guides: website/src/content/docs/guides/frameworks/

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions