I use the following component to create tabs within my project.
function Tab({
children,
className,
fullWidth = true,
...props
}: ExtractProps<typeof HeadlessTab> & {
fullWidth?: boolean;
}) {
const list = useContext(listContext);
const liRef = React.createRef<HTMLLIElement>()
return (
<HeadlessTab as={Fragment}>
{({ selected }) => (
<li
ref={liRef}
className={twMerge([
"focus-visible:outline-none",
fullWidth && "flex-1",
list.variant == "tabs" && "-mb-px",
])}
{...props}
>
<tabContext.Provider
value={{
selected: selected,
}}
>
{typeof children === "function"
? children({
selected: selected,
})
: children}
</tabContext.Provider>
</li>
)}
</HeadlessTab>
);
}
However, I get the following error whenever I try to run the project. I have tried a couple of things such as re-casting the ref to HTMLLIElement while assigning it to the
TS2322: Type 'Ref<HTMLElement>' is not assignable to type 'LegacyRef<HTMLLIElement> | undefined'.
Type 'RefObject<HTMLElement>' is not assignable to type 'LegacyRef<HTMLLIElement> | undefined'.
Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject<HTMLLIElement>'.
Type 'HTMLElement' is missing the following properties from type 'HTMLLIElement': type, value
32 | {({ selected }) => (
33 | <li
> 34 | ref={liRef}
| ^^^
35 | className={twMerge([
36 | "focus-visible:outline-none",
37 | fullWidth && "flex-1",
Not really sure what I am doing wrong with this.
2
Answers
The error message you’re encountering is due to a type mismatch between the type of the
liRef
and the expected type for theref
prop of the<li>
element. Theref
prop is expected to be of typeLegacyRef<HTMLLIElement>
.Try this:
Try this:
import useRef from "react" and replace
"const liRef = React.createRef()"
with the snippet below.
This should help with the type error your getting related to the ref attribute