Guest User

Untitled

a guest
Jul 21st, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. import ReactDOM from "react-dom";
  2. import React from "react";
  3. import _ from "lodash";
  4.  
  5. // --------------------------------
  6. // With width / hegit HOC for D3.js
  7. // --------------------------------
  8.  
  9. const WithSize = Child =>
  10. class extends React.Component {
  11. state = {
  12. width: null,
  13. height: null
  14. };
  15.  
  16. constructor(props) {
  17. super(props);
  18. this.setSize = this.setSize.bind(this);
  19. this.setSizeDebounced = _.debounce(this.setSize, 1000);
  20. window.addEventListener("resize", this.setSizeDebounced);
  21. }
  22.  
  23. componentDidMount() {
  24. this.setSize();
  25. }
  26.  
  27. componentWillUnmount() {
  28. window.removeEventListener("resize", this.setSizeDebounced);
  29. }
  30.  
  31. setSize() {
  32. const width = ReactDOM.findDOMNode(this).clientWidth;
  33. const height = ReactDOM.findDOMNode(this).clientHeight;
  34. this.setState({ width, height });
  35. }
  36.  
  37. render() {
  38. const { width, height } = this.state;
  39. return (
  40. <div style={{ width: "100%", height: "100%" }}>
  41. {width && height ? <Child width={width} height={height} {...this.props} /> : null}
  42. </div>
  43. );
  44. }
  45. };
  46.  
  47.  
  48. // --------------------------------
  49. // Usage
  50. // --------------------------------
  51.  
  52. import React from "react";
  53. import * as d3 from "d3";
  54. import WithSize from "../../shared/with-size";
  55.  
  56. class Chart1 extends React.Component {
  57. static displayName = "D3Chart";
  58. state = {
  59. data: [...],
  60. scaleX: null,
  61. scaleY: null
  62. };
  63.  
  64. componentDidMount() {
  65. this.setState({
  66. scaleX: this.createScaleX(),
  67. scaleY: this.createScaleY()
  68. });
  69. }
  70.  
  71. compomentDidUpdate(prevProps) {
  72. // width / height props from WithSize HOC
  73. if (prevProps.width !== this.props.width || prevProps.height !== this.props.height) {
  74. this.setState({
  75. scaleX: this.createScaleX(),
  76. scaleY: this.createScaleY()
  77. });
  78. }
  79. }
  80.  
  81. createScaleX() {
  82. return d3
  83. .scaleLinear()
  84. .domain([0, d3.max(this.state.data)])
  85. // width / height props from WithSize HOC
  86. .range([0, this.props.width]);
  87. }
  88.  
  89. createScaleY() {
  90. return d3
  91. .scaleBand()
  92. .domain(this.state.data)
  93. // width / height props from WithSize HOC
  94. .range([0, this.props.height])
  95. .padding(0.1);
  96. }
  97.  
  98. render() {
  99. // Render bars, rect etc, use this.state scales
  100. }
  101. }
  102.  
  103. export default WithSize(HorisontalBarChart1);
Add Comment
Please, Sign In to add comment