Allow ref passthrough on CopyToClipboard component
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
import copy from "copy-to-clipboard";
|
import copy from "copy-to-clipboard";
|
||||||
import * as React from "react";
|
import * as React from "react";
|
||||||
|
import { mergeRefs } from "react-merge-refs";
|
||||||
import env from "~/env";
|
import env from "~/env";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
@@ -9,32 +10,40 @@ type Props = {
|
|||||||
onCopy?: () => void;
|
onCopy?: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
class CopyToClipboard extends React.PureComponent<Props> {
|
function CopyToClipboard(props: Props, ref: React.Ref<HTMLElement>) {
|
||||||
onClick = (ev: React.SyntheticEvent) => {
|
const { text, onCopy, children, ...rest } = props;
|
||||||
const { text, onCopy, children } = this.props;
|
|
||||||
const elem = React.Children.only(children);
|
|
||||||
|
|
||||||
copy(text, {
|
const onClick = React.useCallback(
|
||||||
debug: env.ENVIRONMENT !== "production",
|
(ev: React.MouseEvent<HTMLElement>) => {
|
||||||
format: "text/plain",
|
const elem = React.Children.only(children);
|
||||||
});
|
|
||||||
|
|
||||||
onCopy?.();
|
copy(text, {
|
||||||
|
debug: env.ENVIRONMENT !== "production",
|
||||||
|
format: "text/plain",
|
||||||
|
});
|
||||||
|
|
||||||
if (elem && elem.props && typeof elem.props.onClick === "function") {
|
onCopy?.();
|
||||||
elem.props.onClick(ev);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
render() {
|
if (elem && elem.props && typeof elem.props.onClick === "function") {
|
||||||
const { text, onCopy, children, ...rest } = this.props;
|
elem.props.onClick(ev);
|
||||||
const elem = React.Children.only(children);
|
}
|
||||||
if (!elem) {
|
},
|
||||||
return null;
|
[children, onCopy, text]
|
||||||
}
|
);
|
||||||
|
|
||||||
return React.cloneElement(elem, { ...rest, onClick: this.onClick });
|
const elem = React.Children.only(children);
|
||||||
|
if (!elem) {
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return React.cloneElement(elem, {
|
||||||
|
...rest,
|
||||||
|
ref:
|
||||||
|
"ref" in elem
|
||||||
|
? mergeRefs([elem.ref as React.MutableRefObject<HTMLElement>, ref])
|
||||||
|
: ref,
|
||||||
|
onClick,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export default CopyToClipboard;
|
export default React.forwardRef(CopyToClipboard);
|
||||||
|
|||||||
Reference in New Issue
Block a user