리액트 19에서 forwardRef를 deprecate하면서 element의 ref를 관리하는 방법이 바뀌었다.
https://react.dev/blog/2024/04/25/react-19-upgrade-guide
React 19 RC Upgrade Guide – React
The library for web and native user interfaces
react.dev
https://react.dev/blog/2024/04/25/react-19-upgrade-guide
React 19 RC Upgrade Guide – React
The library for web and native user interfaces
react.dev
18버전의 ref 타입 처리
// ref가 HTML 요소인 경우
// React.forwardRef<Ref 요소, 컴포넌트 Props> = (props, ref) => ...
const Button = React.forwardRef<HTMLButtonElement, { disabled: boolean }>(
({ disabled }, ref) => {
return (
<button ref={ref} disabled={disabled} />
);
}
);
// ref가 커스텀 컴포넌트인 경우
// React.forwardRef<
// React.ElementRef<typeof 컴포넌트>,
// React.ComponentPropsWithoutRef<typeof 컴포넌트>
// > = (props, ref) => ...
// shadcn/ui의 ToggleGroup 코드 참조함.
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";
const ToggleGroup = React.forwardRef<
React.ElementRef<typeof ToggleGroupPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root>
>(({ children, ...props }, ref) => (
<ToggleGroupPrimitive.Root
ref={ref}
{...props}
>
{children}
</ToggleGroupPrimitive.Root>
));
19버전의 ref 타입 처리
// ref가 HTML 요소인 경우
// props & { ref?: React.Ref<HTML요소> }
const Button = ({
disabled,
ref
}: {
disabled: boolean;
ref?: React.Ref<HTMLButtonElement>
}) => {
return (
<button ref={ref} disabled={disabled} />
);
}
);
// ref가 커스텀 컴포넌트인 경우
// ({ ref, ...props }: React.ComponentProps<typeof 컴포넌트>) => ...
// shadcn/ui의 ToggleGroup 코드 참조함.
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";
const ToggleGroup = ({
children,
ref,
...props
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root>) => (
<ToggleGroupPrimitive.Root
ref={ref}
{...props}
>
{children}
</ToggleGroupPrimitive.Root>
));