# All files / src/components histogram-x-axis.tsx

100% Statements 16/16
75% Branches 3/4
100% Functions 3/3
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59

    8x

    8x
    4x
    4x

    4x
    4x
    4x
    4x

    4x
    4x
    4x
    4x
    4x

    4x

    4x

     import { useRef, useEffect, useMemo } from 'react';
    import { scaleLinear, axisBottom, select, range } from 'd3';

    import useSize from '../hooks/useSize';

    type Props = {
      /**
       * The start point of the axis
       */
      min: number;
      /**
       * The end point of the axis
       */
      max: number;
      /**
       * Interval size between each tick
       */
      interval: number;
      /**
       * The top offset to vertically shift the axis
       */
      yPos: number;
      /**
       * Label to appear under the axis
       */
      label: string;
    };

    const HEIGHT = 80;

    const XAxis = ({ min, max, interval, yPos, label }: Props) => {
      const d3Container = useRef<SVGSVGElement>(null);
      const [size] = useSize(d3Container);

      useEffect(() => {
        Eif (size?.width && d3Container.current) {
          const scale = scaleLinear().domain([min, max]).range([0, size.width]);
          const axis = axisBottom(scale)
            .tickValues(range(min, max + interval, interval))
            .tickPadding(6);
          axis.tickSize(0);
          const svg = select(d3Container.current);
          svg.selectAll('*').remove();
          svg.append('g').call(axis);
          svg
            .append('text')
            .attr('transform', `translate(${size.width / 2}, ${HEIGHT / 2})`)
            .style('text-anchor', 'middle')
            .text(label);
        }
      }, [interval, label, max, min, size?.width]);

      const style = useMemo(() => ({ top: yPos }), [yPos]);

      return <svg style={style} width="100%" height={HEIGHT} ref={d3Container} />;
    };

    export default XAxis;