All components

SEO JSON-LD

Injects Schema.org BreadcrumbList and Place script tags from GET /v1/seo/json-ld.

Live preview

No JSON-LD for this point.

Install

$bunx shadcn@latest add https://mapbase.dev/r/seo-json-ld.json

The shadcn CLI copies the file(s) below into your tree, installs npm dependencies, and recursively pulls registry dependencies (including from cross-registry URLs).

npm dependencies

mapbase

Registry dependencies

None.

Source

components/mapbase/seo-json-ld.tsx
"use client"

import * as React from "react"
import {
  Mapbase,
  MapbaseError,
  type CountryCode,
  type SeoJsonLdResponse,
} from "mapbase"

import { cn } from "@/lib/utils"

export type SeoJsonLdProps = {
  apiKey: string
  baseUrl?: string
  lng: number
  lat: number
  country?: CountryCode
  siteBaseUrl?: string
  debounceMs?: number
  disabled?: boolean
  /** When true, renders a pretty-printed preview below the script tags. */
  showPreview?: boolean
  className?: string
}

/**
 * Injects Schema.org JSON-LD (`BreadcrumbList` + `Place`) from
 * `GET /v1/seo/json-ld`.
 */
export function SeoJsonLd({
  apiKey,
  baseUrl,
  lng,
  lat,
  country,
  siteBaseUrl,
  debounceMs = 300,
  disabled,
  showPreview = false,
  className,
}: SeoJsonLdProps) {
  const [data, setData] = React.useState<SeoJsonLdResponse | null>(null)
  const [loading, setLoading] = React.useState(false)
  const [error, setError] = React.useState<MapbaseError | null>(null)

  const client = React.useMemo(
    () => new Mapbase(apiKey, baseUrl ? { baseUrl } : undefined),
    [apiKey, baseUrl],
  )

  const countryKey = country ?? ""

  React.useEffect(() => {
    if (disabled) return
    if (!Number.isFinite(lng) || !Number.isFinite(lat)) {
      setData(null)
      setError(null)
      setLoading(false)
      return
    }

    const controller = new AbortController()
    const timer = window.setTimeout(async () => {
      setLoading(true)
      setError(null)

      const response = await client.seo.jsonLd(
        {
          lng,
          lat,
          ...(country ? { country } : {}),
          ...(siteBaseUrl ? { base_url: siteBaseUrl } : {}),
        },
        { signal: controller.signal },
      )

      if (controller.signal.aborted) return

      if (response.error) {
        setError(response.error)
        setData(null)
      } else {
        setData(response.data)
      }
      setLoading(false)
    }, debounceMs)

    return () => {
      controller.abort()
      window.clearTimeout(timer)
    }
  }, [client, lng, lat, countryKey, siteBaseUrl, debounceMs, disabled])

  if (loading) {
    return (
      <p className={cn("text-xs text-muted-foreground", className)}>
        Loading structured data…
      </p>
    )
  }

  if (error) {
    return (
      <p className={cn("text-xs text-destructive", className)} role="alert">
        {error.message}
      </p>
    )
  }

  if (!data) {
    return (
      <p className={cn("text-xs text-muted-foreground", className)}>
        No JSON-LD for this point.
      </p>
    )
  }

  const breadcrumbJson = JSON.stringify(data.breadcrumb_list)
  const placeJson = JSON.stringify(data.place)

  return (
    <div className={cn("flex flex-col gap-2", className)}>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: breadcrumbJson }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: placeJson }}
      />
      {showPreview ? (
        <pre className="overflow-x-auto rounded-md border bg-muted/30 p-3 font-mono text-xs text-muted-foreground">
          {JSON.stringify(
            {
              breadcrumb_list: data.breadcrumb_list,
              place: data.place,
            },
            null,
            2,
          )}
        </pre>
      ) : null}
    </div>
  )
}