Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw d3-axis in react-native

I would like to use

axis = d3.axisLeft(scale)

in a Shape component

<Shape d = {axis()} />

It is common for shape components in d3-shape to return a path if the rendering context is not set, which is the case in React-Native

It is possible to somehow gain acess on the react node context ? The path is not a viable option, since the axis will be a group of items, not a path

like image 739
Alex Huiculescu Avatar asked Jun 13 '18 08:06

Alex Huiculescu


1 Answers

I have been looking into this - my understanding is that it is not possible to use d3-axis and react-native ART Shapes together.

You can use d3-shape with ART Shapes because d3-shape functions return strings that are interpreted by ART Shape. Theses strings are explained well here https://css-tricks.com/svg-path-syntax-illustrated-guide/

So what I have been doing is using that css-tricks article as a reference, and d3-scale, to draw the lines.

This is the basic approach.

1) get an array of data points which you want ticks for.

2) use your d3-scale function from your graph to convert your array of datapoints to there location on the Surface

scalePoints = () => {
    var { xScale, dataPoints } = this.props;
    this.points = [];
    for (var i = 0; i <= dataPoints.length - 1; i++) {
        this.points.push(xScale(dataPoints[i]));
    }
};

3) then you need to use string interpolation and a loop to create the d-string (see the css-tricks article) like this:

getPath = () => {
    var { curveOffsetTop, outerTick, innerTick } = this.props;
    var path = `M0,${curveOffsetTop}`;
    for (var i = 0; i <= this.points.length - 1; i++) {
        path = path + `H${this.points[i]}`;
        path = path + `v${outerTick}`;
        path = path + `v-${outerTick}`;
        path = path + `v-${innerTick}`;
        path = path + `v${innerTick}`;
    }
    return { path: path };
};

4) put this line into your shape like this

<Shape
    {...other}
    d={this.getPath().path}
    stroke="#000"
/>

That is how I have been doing it.

https://github.com/goughjo02/React-Native-Animations-with-PanResponder/blob/master/components/linechart/xAxis.js

like image 182
Joey Gough Avatar answered Oct 15 '22 10:10

Joey Gough