-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to use forwardRef? #72
Comments
You can try to use this way: export type ComponentProps = {
foo?: boolean;
bar: string;
className?: string;
};
export const Component = React.forwardRef(
(props: ComponentProps, ref?: React.Ref<HTMLButtonElement>) => {
const { className, foo, bar } = props;
return (
<button className={className} ref={ref}>
{foo ? bar : 'Buz'}
</button>
);
},
); |
@BoostIO funded this issue with $20. Visit this issue on Issuehunt |
1 similar comment
@BoostIO funded this issue with $20. Visit this issue on Issuehunt |
@BoostIO cancelled funding, $20, of this issue. Visit this issue on Issuehunt |
@issuehuntfest has funded $20.00 to this issue. See it on IssueHunt |
@adrienharnay has submitted a pull request. See it on IssueHunt |
export const Component = React.forwardRef<HTMLButtonElement, ComponentProps>(
(props, ref) => {
return (
<button {...props} ref={ref}>
Submit
</button>
);
}
); |
So @kyle-villeneuve do you have to deconstruct props to make it work? export const Component = React.forwardRef<HTMLButtonElement, ComponentProps>(
(props, ref) => {
return (
<button ref={ref} {...props}>Stuff</button>
);
}
); |
Yes @martisj, just make sure your ComponentProps interface extends |
@IOuser great! thank u |
Brooo |
I'm proposing this updated version instead, which adds usage example and has a more dev friendly displayName in the DevTools: export interface FancyButtonProps {
className?: string;
children?: React.ReactNode;
}
// using function DevTools will show "ForwardRef(FancyButton)" instead of just "ForwardRef"
export const FancyButton = React.forwardRef<HTMLButtonElement, FancyButtonProps>(
function FancyButton(props, ref) {
return (
<button ref={ref} className="FancyButton" {...props} >
{props.children}
</button>
);
}
);
const ref = React.createRef<HTMLButtonElement>();
<FancyButton ref={ref}>Click me!</FancyButton>; |
What is the correct way to type a component which uses
forwardRef
form React 16.3?The text was updated successfully, but these errors were encountered: