Sparklines.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // SPARKLINE
  2. // -----------------------------------
  3. import React, { Component } from 'react';
  4. import PropTypes from 'prop-types';
  5. import $ from 'jquery';
  6. const RESIZE_EVENT = 'resize.sparkline';
  7. /**
  8. * Wrapper for for jquery-sparkline plugin
  9. */
  10. export default class Sparkline extends Component {
  11. static propTypes = {
  12. /** sparkline options object */
  13. options: PropTypes.object.isRequired,
  14. /** tag to use, defaults to div */
  15. tag: PropTypes.string,
  16. /** values to display, allows array or csv string */
  17. values: PropTypes.oneOfType([
  18. PropTypes.string.isRequired,
  19. PropTypes.array.isRequired
  20. ])
  21. }
  22. static defaultProps = {
  23. options: {},
  24. tag: 'div'
  25. }
  26. state = {
  27. values: this.props.values,
  28. options: this.props.options
  29. }
  30. normalizeParams() {
  31. let { options, values } = this.state;
  32. options.disableHiddenCheck = true; // allow draw when initially is not visible
  33. options.type = options.type || 'bar'; // default chart is bar
  34. values = Array.isArray(values) ? values : values.split(','); // support array of csv strings
  35. this.setState({ options, values });
  36. }
  37. componentDidMount() {
  38. this.normalizeParams();
  39. // Sparklines
  40. require('jquery-sparkline/jquery.sparkline.min.js');
  41. // init sparkline
  42. $(this.element).sparkline(this.state.values, this.state.options);
  43. // allow responsive
  44. if (this.state.options.resize) {
  45. $(window).on(RESIZE_EVENT, () => {
  46. $(this.element).sparkline(this.state.values, this.state.options);
  47. });
  48. }
  49. }
  50. componentWillUnmount() {
  51. $(window).off(RESIZE_EVENT);
  52. $(this.element).sparkline('destroy');
  53. }
  54. setRef = node => {
  55. this.element = node;
  56. }
  57. render() {
  58. const {tag:Tag} = this.props;
  59. return (
  60. <Tag ref={this.setRef} {...this.props}></Tag>
  61. )
  62. }
  63. }