Published on

Hello Charts!

0 views
Authors
  • Name
    Twitter

Alright, I had spare time today during lunch, and I decided to quickly try and add a useful feature to the blog engine that I am using: dynamic charts.

What that means is that now I can embed, directly in my .mdx files, a piece of JavaScript code that will be passed to a component and used to render a chart.

Here's an example, showing the price of Ethereum in the last 30 days:

The code? It's available on GitHub. Here's the code embedded in this MDX file, to show how easy it is now to add a line chart:

export const url = `https://api.coingecko.com/api/v3/coins/ethereum/market_chart?vs_currency=eur&days=30&interval=hourly`

export const mapper = (data) => {
  const { prices, market_caps, total_volumes } = data
  const ret = [
    {
      id: 'EUR',
      color: 'hsl(341, 70%, 50%)',
      data: [],
    },
  ]
  const values = prices.map((price, i) => {
    const date = new Date(price[0])
    const xAxis =
      ('0' + date.getUTCDate()).slice(-2) +
      '/' +
      ('0' + date.getUTCMonth()).slice(-2) +
      ' ' +
      ('0' + date.getUTCHours()).slice(-2) +
      ':00'
    return {
      x: xAxis,
      y: price[1],
    }
  })
  ret[0].data = values
  return ret
}

<MDXLineChart url={url} mapper={mapper} />