Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 v4 + react + ES6: How to create axis programmatically?

I am trying to get my head around d3 in its current version 4. Specifically: I a trying to create the x axis for a simple line chart in react and es6.

I have seen the examples of Mike Bostock and how he does it:

svg.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));

But that is neither react nor ES6.

On another site I have seen the following variant:

renderAxis() {
  var node  = this.refs.axis;
  var axis = d3.svg.axis().orient(this.props.orient).ticks(5).scale(this.props.scale);
  d3.select(node).call(axis);
}

render() {
  return <g className="axis" ref="axis" transform={this.props.translate}></g>
}

This is react and ES6 but not d3 in version 4.

I could try to adopt the version 3 code to version 4 of d3 but: The d3.select bothers me extremely. I don't want to make DOM-calls when I am using react (or some other library within, like d3). React should be used to render into the DOM in the most efficient way, not to get me DOM nodes.

So, my question is: What is the react-way to create me a simple x axis? Or, if there is yet not such an answer: What is the react way to adopt the quoted code of Mike Bostock?

like image 216
hurrtz Avatar asked Jul 14 '16 18:07

hurrtz


1 Answers

After a couple years of trying to figure out d3 in React, this is the best way my team and I have found of doing axes:

const Axis = props => {
    const axisRef = axis => {
        axis && props.axisCreator(select(axis));
    };

    return <g className={props.className} ref={axisRef} />;
};

Notes

  • axisCreator is the function returned by axisBottom, axisLeft, etc. It is created outside the component to expose to the user the full power of the d3-axis library.
  • className allows the user to style the axis however he or she wants.
  • This example uses refs, which the React docs caution against, but it uses refs to integrate with a third-party DOM library, which is one of the reasons to use refs that the React docs call out specifically.
  • It is understandable that using d3's select bothers you, but it's required if you want to let d3 manipulate the DOM, and if you don't let d3 manipulate the DOM, you lose out on all the functionality of d3 (which is an incredibly cool library).
like image 56
Dominus.Vobiscum Avatar answered Sep 26 '22 19:09

Dominus.Vobiscum