Using arrow functions with D3
Arrow functions are one of the most recognizable and popular parts of ES6 for good reason. Their terse syntax makes writing functions quick and easy, and they offer quite a bit of expressiveness.
Some of their features, like implicit returns, make them perfect for use with D3. Compare these examples that accomplish the same thing and it's easy to see why an arrow function is often the obvious choice.
// becomes
But...
Arrow functions also have a lexical this
. This usually comes in handy, but it introduces some caveats when working with D3. Normally, when you pass a function to most D3 APIs (like selection.attr) it will bind this
to the DOM element being operated on. That won't work with arrow functions, so you have two choices of how to work around it.
The first option is to just use a regular function. (Does that count as a work around?) It's fairly rare that you need to access a DOM element directly, so reverting to the venerable function
keyword every now and then is a completely reasonable solution.
The other option is to define your arrow function so that it accepts a third parameter. You're probably used to defining these types of functions with only one parameter, the datum, or in some cases two, which gets you the index as well. The third parameter is the current group, usually specified as nodes
. You can then use the index parameter to access the current node, just like this
in a normal function.
// becomes
The approach you choose is totally up to you. Happy hacking!