Manual Reference Source

basic/dataTable/TableColumn.js

  1. /**
  2. * Created by pawelposel on 17/11/2016.
  3. */
  4.  
  5. import PropTypes from 'prop-types';
  6.  
  7. import React, { Component } from 'react';
  8.  
  9. /**
  10. * Defines table columns, renders <th> elements.
  11. *
  12. * ## Access
  13. * `Stage.Basic.DataTable.Column`
  14. *
  15. * ## Usage
  16. *
  17. * ```
  18. * <DataTable.Column label="Name" name="id" width="40%"/>
  19. * ```
  20. */
  21. export default class TableColumn extends Component {
  22. /**
  23. * @property {any} label - column label
  24. * @property {string} [name] - data property, enables column sorting
  25. * @property {string} [width] - width style
  26. * @property {boolean} [show=true] - if false then column is hidden
  27. * @property {boolean} [centerAligned=false] - if true then column label is center aligned
  28. */
  29. static propTypes = {
  30. label: PropTypes.any,
  31. name: PropTypes.string,
  32. width: PropTypes.string,
  33. show: PropTypes.bool,
  34. centerAligned: PropTypes.bool
  35. };
  36.  
  37. static defaultProps = {
  38. width: '',
  39. show: true,
  40. centerAligned: false
  41. };
  42.  
  43. static contextTypes = {
  44. getSortColumn: PropTypes.func.isRequired,
  45. isSortAscending: PropTypes.func.isRequired,
  46. sortColumn: PropTypes.func.isRequired
  47. };
  48.  
  49. _onClick() {
  50. if (this.props.name) {
  51. this.context.sortColumn(this.props.name);
  52. }
  53. }
  54.  
  55. _className() {
  56. let cssClass = this.props.name ? '' : 'disabled';
  57.  
  58. if (this.context.getSortColumn() === this.props.name) {
  59. cssClass += ' sorted';
  60. cssClass += this.context.isSortAscending() ? ' ascending' : ' descending ';
  61. }
  62.  
  63. if (this.props.centerAligned) {
  64. cssClass += ' center aligned';
  65. }
  66.  
  67. return cssClass;
  68. }
  69.  
  70. render() {
  71. if (!this.props.show) {
  72. return null;
  73. }
  74.  
  75. return (
  76. <th
  77. className={this._className()}
  78. style={this.props.width ? { width: this.props.width } : {}}
  79. onClick={this._onClick.bind(this)}
  80. >
  81. {this.props.label}
  82. </th>
  83. );
  84. }
  85. }