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?
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.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).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With