Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6213

Typing incompatibility between useRef() and d3.drag() in React-native

$
0
0

I have a weird typing issue that's been driving me crazy for the last two days. I hope you can save my sanity :D!

Stack : react-native (Functional Component oriented) + typescriptLibs involved: react-native-svg, d3

I would like to create a "DraggableCircle" Component that extends the Component Circle from react-native-svg. I chose to use d3 instead of PanResponder because I already knew a bit about the lib.

Here is my code:

import React, { useEffect, useRef, Component } from 'react';import { Circle, CircleProps } from 'react-native-svg';import * as d3 from 'd3';type IProps = CircleProps;const DraggableCircle: React.FC<IProps> = (props: IProps) => {  const circleRef = useRef(null);  useEffect(() => {    if (circleRef.current) {      const circle = d3.select(circleRef.current);      circle.call(        d3.drag().on('start', () => {          console.log('ok');        }),      );    }  }, [circleRef]);  return <Circle {...props} ref={circleRef} />;};export default DraggableCircle;

What I see :Screen capture of the error

I use eslint which allows me to catch errors. Eslint indicates an error in d3.drag() :Type 'Selection<null, unknown, null, undefined>' is not assignable to type 'Selection<Element, unknown, any, any>'.

So I understand that I have to type useRef() so that it considers the element that will be referenced not as null, but as an Element.

What I've tried:const circleRef = useRef<SVGCircleElement>(null);const circleRef = useRef<CircleProps>(null);const circleRef = useRef<Element>(null);

With each of these three typings, I have no more errors on the d3.drag().On the other hand, I have a new typing error on ref={circleRef} :Type 'RefObject' is not assignable to type 'RefObject<Component<CircleProps, any, any>>>'.

What I've tried:const circleRef = useRef<Component<CircleProps>>(null);

This removes the error on the ref, but I immediately find the error on the d3.drag() (which makes sense to me...)So I have the impression that the types expected by d3.drag() and by ref are incompatible. After a lot of searching I couldn't find any help in this sense. It seems that most people don't have this problem.

Any idea?=> If you have a completely different solution to propose to create a draggable element, I'm interested too, even if I'd like to avoid turning to PanResponder which doesn't seem to be easy to understand.

Thank you in advance.


Viewing all articles
Browse latest Browse all 6213

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>