Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React v16- d3 v4, when using mouse from d3-selection will get, TypeError: Cannot read property 'sourceEvent' of null?

Using d3 with React and importing mouse from d3-selection

import { selectAll, select, mouse } from 'd3-selection';

when trying use : mouse(e.target) or mouse(select('.element')) in the component, I get this error:

TypeError: Cannot read property 'sourceEvent' of null
./node_modules/d3-selection/src/sourceEvent.js.__webpack_exports__.a
node_modules/d3-selection/src/sourceEvent.js:5
  2 | 
  3 | export default function() {
  4 |   var current = event, source;
> 5 |   while (source = current.sourceEvent) current = source;
  6 |   return current;
  7 | }
  8 | 

The project created using react-create-app, seems source event is not accessed?...

like image 686
Alireza Avatar asked Jan 03 '18 18:01

Alireza


1 Answers

The best solution after some researching is this, as I'm not using d3-events, we should pass the event through the call to fix the problem...

var mouse = function(node) {
  var event = sourceEvent();
  if (event.changedTouches) event = event.changedTouches[0];
  return point(node, event);
};

d3.mouse does not accept event as arguments, but if you read the source code, you can find another function which gets called through mouse(), to return the value and it accepts event as an argument, this function called clientPoint().

So instead of using mouse(), use clientPoint()...

In my case this worked:

import { selectAll, select, clientPoint } from 'd3-selection';

And:

myFunction(e){
  console.log(clientPoint(e.target, e));
}

I passed both element and event in this case as clientPoint (called point in the code, but exported as clientPoint) will accept (node, event) as you see in the source code:

var point = function(node, event) {
  var svg = node.ownerSVGElement || node;

  if (svg.createSVGPoint) {
    var point = svg.createSVGPoint();
    point.x = event.clientX, point.y = event.clientY;
    point = point.matrixTransform(node.getScreenCTM().inverse());
    return [point.x, point.y];
  }

  var rect = node.getBoundingClientRect();
  return [event.clientX - rect.left - node.clientLeft, event.clientY - rect.top - node.clientTop];
};

Hope this help somebody else using React v16 with D3 v4...

like image 176
Alireza Avatar answered Sep 18 '22 15:09

Alireza