@tinybirdco/charts
TypeScript icon, indicating that this package has built-in type declarations

0.1.5 • Public • Published

@tinybirdco/charts (beta)

@tinybirdco/charts is a charting library for React applications, designed to make it easy to create and customize a variety of charts using data from your Tinybird. endpoints. The library leverages the power of Echarts and SWR for efficient data fetching and visualization.

@tinybirdco/charts is currently in public beta. It is not feature-complete and may change in the future. If you have any feedback or suggestions, please join us in the Slack community.

Installation

To install the library, run:

npm install @tinybirdco/charts

Usage

Chart components

You can directly use a chart component by passing its required props:

import React from 'react'
import { LineChart } from '@tinybirdco/charts'

function MyLineChart() {
  return (
    <LineChart
      categories={['category1', 'category2']}
      index="index_field"
      title="My Line Chart"
      description="This is a line chart"
      showLegend={true}
      height={400}
      width="100%"
      endpoint="https://api.tinybird.co/v0/pipes/my_pipe.json"
      token="your_tinybird_token"
      params={{ filter: 'value' }}
      backgroundColor="#fff"
      textColor="#333"
      borderRadius="8px"
    />
  )
}

Reusing styles and query config using the ChartProvider

You can wrap components within <ChartProvider> to share styles, query configuration and custom loading and error states among several charts.

function App() {
  return (
    <ChartProvider
      styles={{
        backgroundColor: '#fff',
        textColor: '#333',
        colorPalette: ['#5470c6', '#91cc75', '#fac858']
      }}
      queryConfig={{
        endpoint: 'https://api.tinybird.co/v0/pipes/my_pipe.json',
        token: 'your_tinybird_token',
        refreshInterval: 10000
      }}
      fallbacks={{
        loading: <div>Loading...</div>,
        error: ({ error }) => <div>Error: {error}</div>
      }}
    >
      <LineChart title="KPIS" index="date" categories={['visits', 'hits']} />
      <BarChart title="Top devices" index="device" categories={['visits', 'hits']} />
    </ChartProvider>
  )
}

Adding extra behavior to the fetcher

You can add your own fetcher to the ChartProvider or to a specific chart component using the fetcher prop. This can be useful to add custom headers or dealing with JWT tokens.

function App() {
  return (
    <ChartProvider
      queryConfig={{
        endpoint: 'https://api.tinybird.co/v0/pipes/my_pipe.json',
        token: getToken(),
        fetcher: async endpoint => {
          const url = new URL(endpoint)
          const response = await fetch(url)
          if (!response.ok) {
            if (response.status === 401) {
              const refreshedToken = await refreshToken()
              url.searchParams.set('token', refreshedToken)
              return fetch(url).then(res => res.json())
            } else {
              throw new Error(await response.text())
            }
          }
          return response.json()
        }
      }}
    >
      <LineChart title="KPIS" index="date" categories={['visits', 'hits']} />
      <BarChart title="Top devices" index="device" categories={['visits', 'hits']} />
    </ChartProvider>
  )
}

Using the hook

You can use the useQuery hook to fetch data and pass it directly to the component:

import React from 'react'
import { LineChart, useQuery } from '@tinybirdco/charts'

function MyHookLineChart() {
  const { data, error, loading } = useQuery({
    endpoint: 'https://api.tinybird.co/v0/pipes/my_pipe.json',
    token: 'your_tinybird_token',
    params: { filter: 'value' }
  })

  if (loading) return <div>Loading...</div>
  if (error) return <div>Error: {error}</div>

  return (
    <LineChart
      categories={['category1', 'category2']}
      index="index_field"
      title="My Line Chart"
      description="This is a line chart"
      showLegend={true}
      height={400}
      width="100%"
      data={data}
    />
  )
}

export default MyHookLineChart

Extra personalization using ECharts options

You can pass extra options to the Echarts instance using the options prop. This can be useful to customize the chart appearance or behavior.

import { AreaChart } from '@tinybirdco/charts'

function ExtraOptionsChart() {
  return (
    <AreaChart
      categories={['category1', 'category2']}
      index="index_field"
      title="Extra Options Chart"
      height={400}
      width="100%"
      endpoint="https://api.tinybird.co/v0/pipes/my_pipe.json"
      token="your_tinybird_token"
      options={{
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%'
        },
        animation: true,
        animationDuration: 1000,
        tooltip: {
          backgroundColor: '#fff',
          textStyle: {
            color: '#333'
          }
        }
      }}
    />
  )
}

You can also use the useQuery hook to retrieve the data from the endpoint, so you can render the data as you wish or using other chart libraries.

Components

The library provides the following chart components:

  • AreaChart
  • BarChart
  • BarList
  • DonutChart
  • LineChart
  • PieChart
  • Table

All components share the same API, making it easy to switch between different types of charts.

API

Component props

Data fetching:

  • endpoint: String. The Tinybird endpoint to fetch data from. Only required if data is not provided.
  • token: String. The Tinybird token to use for authentication. Only required if endpoint is provided.
  • params: Object. Additional parameters to pass to the Tinybird endpoint.
  • refreshInterval: Number. The interval in milliseconds to refresh the data.
  • loading: Boolean. Whether the chart is in a loading state.
  • error: String or null. Error message if the chart failed to load.
  • fallbackLoading: React element. The loading fallback component.
  • fallbackError: React element. The error fallback component.
  • onSuccess: Function. Callback function to run when the data is successfully fetched.
  • onError: Function. Callback function to run when the data fails to fetch.

Data:

  • categories: Array of strings. The categories to display on the chart.
  • index: String. The field to use as the index for the chart.
  • title: String. The title of the chart.
  • description: String. The description of the chart.
  • data: Array of objects. The data to display on the chart.
  • meta: Array of objects. Metadata about the chart data.
  • stacked: Boolean. Whether to stack the chart bars/areas.
  • groupBy: String. The field to group the data by.
  • options: Object. Additional options for Echarts.

Styling:

  • height: Number or String. The height of the chart.
  • width: Number or String. The width of the chart.
  • backgroundColor: String. The background color of the chart.
  • borderColor: String. The border color of the chart.
  • borderRadius: Number or String. The border radius of the chart.
  • boxShadow: String. The box shadow of the chart.
  • colorPalette: Array of strings. The color palette for the chart.
  • fontFamily: String. The font family for the chart.
  • fontSize: Number or String. The font size for the chart.
  • padding: Number or String. The padding for the chart.
  • textColor: String. The text color for the chart.
  • showLegend: Boolean. Whether to show the legend.

Hooks

useQuery

The useQuery hook is a custom hook that fetches data from a Tinybird endpoint and returns the data, error, and loading state.

import { useQuery } from '@tinybirdco/charts'

function MyComponent() {
  const { data, error, loading } = useQuery({
    endpoint: 'https://api.tinybird.co/v0/pipes/my_pipe.json',
    token: 'your_tinybird_token',
    params: { filter: 'value' }
  })

  if (loading) return <div>Loading...</div>
  if (error) return <div>Error: {error}</div>

  return <div>{JSON.stringify(data)}</div>
}

Readme

Keywords

none

Package Sidebar

Install

npm i @tinybirdco/charts

Weekly Downloads

186

Version

0.1.5

License

MIT

Unpacked Size

84.5 kB

Total Files

68

Last publish

Collaborators

  • rmorehig
  • sdairs
  • alejandromav
  • xavijam
  • jamedina
  • ivanmalagon