Skip to content

Instantly share code, notes, and snippets.

@nikolay-borzov
Created March 26, 2019 12:36
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikolay-borzov/8d352ce5468548a211e6c7f731b64751 to your computer and use it in GitHub Desktop.
Save nikolay-borzov/8d352ce5468548a211e6c7f731b64751 to your computer and use it in GitHub Desktop.
const Button = forwardRef<CoralButton, ButtonProps>((props, ref) => {
const { children, onClick, title, ...coralButtonProps } = props;
const buttonRef = useRef<CoralButton>(null);
useLayoutEffect(() => {
if (ref) {
if (isFunction(ref)) {
ref(buttonRef.current);
} else {
(ref as any).current = buttonRef.current;
}
}
}, [buttonRef]);
useEffect(() => {
const button = buttonRef.current!;
if (onClick) {
button.addEventListener('click', onClick);
return () => {
button.removeEventListener('click', onClick);
};
}
}, [onClick]);
return (
<coral-button
ref={buttonRef}
title={title}
{...getCustomElementAttributes(coralButtonProps)}>
{children}
</coral-button>
);
});
@phwb
Copy link

phwb commented Jul 2, 2019

Just use useImperativeHandle https://ru.reactjs.org/docs/hooks-reference.html#useimperativehandle

code sample, see ChildInput.tsx component

@nikolay-borzov
Copy link
Author

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment