Search code examples
svgreactjsreact-d3

React D3 x-axis text tilt - how to access transform property? tickFormat?


I am using the Bar Chart in React-D3 :

My x-axis labels are slamming into each other, and I want to rotate them for readability,

an issue solved here for D3 without React rendering: http://www.d3noob.org/2013/01/how-to-rotate-text-labels-for-x-axis-of.html

How do I fit this solution into the React-D3 package?

Where can I access the 'transform' property on 'text' or 'tick'?

I tried to pass in a prop as 'xAxisTransform' on BarChart.js, but it wasn't registering.

Should I use the tickFormat function to change the text on the ticks, if so, how?

Can/should ticks be manipulated from /common/axes/AxisTicks.js ? https://github.com/esbullington/react-d3/issues/162


Solution

  • In node_modules/react-D3/common/axes/AxisTicks.js there's a switch statement (depending on where axis ticks are located on graph) where transform = rotate(-65) can be added.

    Make sure to declare transform as a variable:

    render:function() {
        var props = this.props;
    
        var tr,
            ticks,
            scale,
            adjustedScale,
            textAnchor,
            transform,
            tickFormat,
            y0, y1, y2, dy, x0, x1, x2, dx;
    

    and at bottom where the element is created by React and returned add it to the style object:

    React.createElement("text", {
          strokeWidth: "0.01", 
          dy: dy, x: x1, y: y1, 
          style: {stroke:props.tickTextStroke, fill:props.tickTextStroke}, 
              textAnchor: textAnchor,
              transform: transform
          }
    

    This solves the immediate problem, however, hacks the shared/common attributes for all D3 chart axis ticks.

    If there is a better way, please post!