Vandhana
Vandhana

Reputation: 521

Highcharts Sparkline in reactjs without Jquery

The sample code given for Highcharts Sparkline uses jquery.(https://www.highcharts.com/demo/sparkline)

But I should not use jquery in my project. I wrote a code in react js to accept the data dynamically from another file and render the table.I have no idea how to implement the sparkline chart without using jquery references.

Can someone please help me with it?

Upvotes: 0

Views: 1771

Answers (2)

Abdul Hameed
Abdul Hameed

Reputation: 103

My suggestion for your scenario is to use REACT_SPARKLINES instead of highcharts which is too easy to implement.

https://github.com/borisyankov/react-sparklines

view this link and rock

Upvotes: 0

morganfree
morganfree

Reputation: 12472

I rewrote the demo to React. It is available on github here. You can also see it live in React sandbox - here.

So I created two components:

  • SparkLine which builds a chart from the given options
  • SparkLineTable which takes the tables rows (children) and transform them to a chart if they have data-sparkline attribute

So app as follows:

import React from 'react';
import { render } from 'react-dom';
import SparkLineTable from './components/SparkLineTable.jsx';

const App = () =>
  <SparkLineTable>
    <thead>
      <tr>
        <th>State</th>
        <th>Income</th>
        <th>Income per quarter</th>
        <th>Costs</th>
        <th>Costs per quarter</th>
        <th>Result</th>
        <th>Result per quarter</th>
      </tr>
    </thead>
    <tbody id="tbody-sparkline">
      <tr>
        <th>Alabama</th>
        <td>254</td>
        <td data-sparkline="71, 78, 39, 66 " />
        <td>296</td>
        <td data-sparkline="68, 52, 80, 96 " />
        <td>-42</td>
        <td data-sparkline="3, 26, -41, -30 ; column" />
      </tr>
    </tbody>
  </SparkLineTable>;

render(<App />, document.getElementById('app'));

gives the output like this:

highcharts-sparkline-react

The part which transforms <td> to <SparkLine />:

toSparkLine(children) {
  let header

  return React.Children.map(children, child => {
    if (!React.isValidElement(child)) return child

    if (child.type === 'th') header = child.props.children

    if (child.props['data-sparkline']) {
      return this.sparkLine(child, header)
    }

    if (child.props.children) {
      child = React.cloneElement(child, {
        children: this.toSparkLine(child.props.children)
      })
    }

    return child
  })
}

sparkLine(element, header) {
  const dataAttr = element.props['data-sparkline'].split('; ')

  const data = dataAttr[0].split(', ').map(Number)
  const options = {
    series: [{
      data,
      pointStart: 1
    }],

    tooltip: {
      headerFormat: `<span style="font-sze:10px">${header}, Q{point.x}: </span><br/>`,
      pointFormat: '<b>{point.y}.000</b> USD'
    },
    chart: {
      type: dataAttr[1] || 'area'
    }
  }

  return <SparkLine options={options} />
}

Upvotes: 1

Related Questions