react-redux-typescript-guide
react-redux-typescript-guide copied to clipboard
How to use forwardRef?
What is the correct way to type a component which uses forwardRef
form React 16.3?
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
@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? Can't do this?
export const Component = React.forwardRef<HTMLButtonElement, ComponentProps>(
(props, ref) => {
return (
<button ref={ref} {...props}>Stuff</button>
);
}
);
So @kyle-villeneuve do you have to deconstruct props to make it work? Can't do this?
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 React.HTMLProps<HTMLButtonElement>
@IOuser great! thank u
export const Component = React.forwardRef<HTMLButtonElement, ComponentProps>( (props, ref) => { return ( <button {...props} ref={ref}> Submit </button> ); } );
Brooo <3 <3 <3
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>;