ClickToCopy.jsx 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import React, { useState, useRef } from "react";
  2. import styled from "styled-components";
  3. const Container = styled.div`
  4. position: relative;
  5. display: inline-flex;
  6. justify-content: center;
  7. `
  8. const UnderlinedSpan = styled.span`
  9. border-bottom: 1px dashed #bbb;
  10. `
  11. const ToolTip = styled.span`
  12. background-color: black;
  13. color: white;
  14. text-align: center;
  15. padding: 2px 8px;
  16. border-radius: 8px;
  17. position: absolute;
  18. z-index: 1;
  19. top: -115%;
  20. white-space: nowrap;
  21. transition: opacity 0.25s;
  22. opacity: ${({ show }) => show ? 0.75 : 0};
  23. `
  24. const InvisbleTextarea = styled.textarea`
  25. position: absolute;
  26. top: -10000px;
  27. z-index: -10000;
  28. opacity: 0;
  29. `
  30. export default ({ text, children }) => {
  31. const textareaRef = useRef(null);
  32. const [hovered, setHovered] = useState(false);
  33. const [copied, setCopied] = useState(false);
  34. const onClick = () => {
  35. textareaRef.current.select();
  36. document.execCommand("copy");
  37. setCopied(true);
  38. }
  39. const onHover = () => {
  40. setCopied(false);
  41. setHovered(true);
  42. }
  43. const onUnhover = () => {
  44. setHovered(false);
  45. }
  46. return (
  47. <Container>
  48. <UnderlinedSpan onClick={onClick} onMouseOver={onHover} onMouseOut={onUnhover}>
  49. {children ? children : text}
  50. </UnderlinedSpan>
  51. <ToolTip show={hovered}>
  52. {copied ? "Copied!" : "Click to Copy"}
  53. </ToolTip>
  54. <InvisbleTextarea ref={textareaRef} value={text} readOnly />
  55. </Container>
  56. )
  57. }