React ref types

Hey. I'm having some difficulty trying to set a type for a ref in React that can be applied to any HTML element.
13 Replies
domi?
domi?•3y ago
My current implementation:
const ref = useRef<HTMLElement>(null);

// ...

<div ref={ref}>
// ...
</div>
const ref = useRef<HTMLElement>(null);

// ...

<div ref={ref}>
// ...
</div>
But TypeScript doesn't like that: Type 'RefObject<HTMLElement>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?•3y ago
I'm trying to create a custom hook that will work with pretty much any HTML element hm, let me try that no, it didn't help the situation, ts is still complaining
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?•3y ago
import React, { useRef } from 'react';


function useHook() {
const ref = useRef<HTMLElement>(null);

return { ref };
}

const Component: React.FC = () => {
const { ref } = useHook();

return (
<div ref={ref}>text</div>
);
};


export { useHook, Component };
import React, { useRef } from 'react';


function useHook() {
const ref = useRef<HTMLElement>(null);

return { ref };
}

const Component: React.FC = () => {
const { ref } = useHook();

return (
<div ref={ref}>text</div>
);
};


export { useHook, Component };
domi?
domi?•3y ago
yeah, but I'd like to be able to use this hook on another element if needed. Let's say a span or n ul later on
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?•3y ago
Using any kind of defeats the purpose of ts here but thanks for the info. I'll keep experimenting 👀
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?•3y ago
hm that's a good idea
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
domi?
domi?•3y ago
this method works well, thanks
Unknown User
Unknown User•3y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server