umami/components/common/CopyButton.js

38 lines
890 B
JavaScript
Raw Normal View History

2020-08-08 05:36:57 +02:00
import React, { useState } from 'react';
import PropTypes from 'prop-types';
2020-08-08 05:36:57 +02:00
import Button from './Button';
2020-09-06 02:27:01 +02:00
import { FormattedMessage } from 'react-intl';
2020-08-08 05:36:57 +02:00
2020-09-06 02:27:01 +02:00
const defaultText = (
2020-10-13 07:53:59 +02:00
<FormattedMessage id="label.copy-to-clipboard" defaultMessage="Copy to clipboard" />
2020-09-06 02:27:01 +02:00
);
2020-08-08 05:36:57 +02:00
function CopyButton({ element, ...props }) {
2020-08-08 05:36:57 +02:00
const [text, setText] = useState(defaultText);
function handleClick() {
if (element?.current) {
element.current.select();
document.execCommand('copy');
2020-09-06 02:27:01 +02:00
setText(<FormattedMessage id="message.copied" defaultMessage="Copied!" />);
2020-08-08 05:36:57 +02:00
window.getSelection().removeAllRanges();
}
}
return (
<Button {...props} onClick={handleClick}>
{text}
</Button>
);
}
CopyButton.propTypes = {
element: PropTypes.shape({
current: PropTypes.shape({
select: PropTypes.func.isRequired,
}),
}),
};
export default CopyButton;