Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. import React, { useState } from "react";
  2. import { useInView } from "react-intersection-observer";
  3. import PropTypes from "prop-types";
  4.  
  5. const Img = ({
  6. src,
  7. srcSet,
  8. placeholder,
  9. width,
  10. height,
  11. alt = "",
  12. title = "",
  13. style
  14. }) => {
  15. const [imgLoaded, setLoaded] = useState(false);
  16. const [ref, inView] = useInView({
  17. threshold: 0,
  18. triggerOnce: true
  19. });
  20.  
  21. const wrapperStyles = Object.assign(
  22. {
  23. position: `relative`,
  24. overflow: `hidden`
  25. },
  26. style
  27. );
  28.  
  29. const paddingDivStyles = {
  30. width: `100%`,
  31. paddingBottom: `
  32. ${(Math.min(width, height) / Math.max(width, height)) * 100}%`
  33. };
  34.  
  35. return (
  36. <div ref={ref} style={wrapperStyles}>
  37. {/* PADDING */}
  38. <div style={paddingDivStyles} />
  39. {inView && (
  40. <>
  41. {/* PLACEHOLDER */}
  42. <img
  43. src={placeholder}
  44. style={{
  45. position: `absolute`,
  46. top: 0,
  47. left: 0,
  48. width: `100%`,
  49. height: `100%`,
  50. objectFit: `cover`,
  51. objectPosition: `center center`,
  52. transition: `opacity 500ms 500ms ease`,
  53. opacity: imgLoaded ? 0 : 1
  54. }}
  55. alt={alt}
  56. title={title}
  57. />
  58. {/* IMAGE */}
  59. <img
  60. srcSet={srcSet}
  61. src={src}
  62. alt={alt}
  63. style={{
  64. position: `absolute`,
  65. top: 0,
  66. left: 0,
  67. width: `100%`,
  68. height: `100%`,
  69. objectFit: `cover`,
  70. objectPosition: `center center`,
  71. transition: `opacity 500ms ease`,
  72. opacity: imgLoaded ? 1 : 0
  73. }}
  74. onLoad={() => setLoaded(true)}
  75. alt={alt}
  76. title={title}
  77. />
  78. </>
  79. )}
  80. </div>
  81. );
  82. };
  83.  
  84. Img.propTypes = {
  85. src: PropTypes.string.isRequired,
  86. srcSet: PropTypes.string.isRequired,
  87. width: PropTypes.number.isRequired,
  88. height: PropTypes.number.isRequired,
  89. alt: PropTypes.string,
  90. title: PropTypes.string
  91. };
  92.  
  93. export default Img;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement