I have a component that has a dynamic tag name which can be either div
or fieldset
depending on the value of the group
prop that’s returned from our useForm
hook.
const FormGroup = React.forwardRef<
HTMLFieldSetElement | HTMLDivElement,
React.HTMLAttributes<HTMLFieldSetElement | HTMLDivElement>
>(({ children, className, ...props }, ref) => {
const { group } = useForm();
const Component = group ? "fieldset" : "div";
return (
<Component ref={ref} className={className} {...props}>
{children}
</Component>
);
});
However it returns an error that ref
is not assignable… I tried using:
const Component = group ? "fieldset" : "div" as keyof JSX.IntrinsicElements;
Is there a clean way to type check a dynamic tag name that’s using a ref?
2
Answers
You can use conditional types and a type assertion to ensure the correct typing.
This is my approach