someuser2491
someuser2491

Reputation: 1978

How to add ref to a react styled component div using react and typescript?

i want to add ref to styled component div.

My code is like below,

const DragAndDrop: React.FC<any> = props => {
    const div_ref= React.createRef();
    return (
        <Zone ref={div_ref}/>
    );
}

But this gives me error

Type RefObject is not assignable to type {instance: htmlDivElement || null} => void || refObject|| null || undefined

could someone help me fix this. thanks.

Upvotes: 0

Views: 1951

Answers (1)

wentjun
wentjun

Reputation: 42566

If you are working with functional components, you should be using the useRef hook instead, and initialise it with a value of null.

const DragAndDrop: React.FC<any> = (props) => {
  const div_ref= useRef(null);

  return (
    <Zone ref={div_ref}/>
  );
}

In addition, try not to use any for the type genetic parameter of your component.

Upvotes: 0

Related Questions