Source: react-imready/src/react-imready/useImReady.tsx

  1. import { MutableRefObject, Ref, RefCallback } from "react";
  2. import { ImReadyReactiveProps, REACTIVE_IMREADY } from "@egjs/imready";
  3. import { useReactive, ReactiveAdapterResult } from "@cfcs/react";
  4. export interface ReactImReadyResult extends ReactiveAdapterResult<typeof REACTIVE_IMREADY> {
  5. register<T extends HTMLElement>(ref?: Ref<T>): RefCallback<T>;
  6. }
  7. /**
  8. * React hook to check if the images or videos are loaded.
  9. * @ko 이미지와 비디오들이 로드가 됐는지 체크하는 react hook.
  10. * @memberof ReactImReady
  11. * @param - React ImReady's props </ko>React ImReady의 props.</ko>
  12. * @example
  13. * ```js
  14. * import { useImReady } from "@egjs/react-imready";
  15. *
  16. * function App() {
  17. * const {
  18. * register,
  19. * isReady,
  20. * isPreReady,
  21. * preReadyCount,
  22. * readyCount,
  23. * totalCount,
  24. * } = useImReady({
  25. * selector: "img",
  26. * });
  27. * // &lt;div ref={register()}&gt;&lt;/div&gt;
  28. * }
  29. * ```
  30. */
  31. export function useImReady(props: Partial<ImReadyReactiveProps> = {}): ReactImReadyResult {
  32. const result = useReactive(REACTIVE_IMREADY, () => props);
  33. return Object.assign(result, {
  34. register<T extends HTMLElement>(ref?: Ref<T>) {
  35. return (instance: T | null) => {
  36. if (instance) {
  37. result.add(instance);
  38. }
  39. if (!ref) {
  40. return;
  41. }
  42. const refType = typeof ref;
  43. if (refType === "function") {
  44. (ref as RefCallback<T>)(instance);
  45. } else {
  46. (ref as MutableRefObject<T | null>).current = instance;
  47. }
  48. };
  49. },
  50. });
  51. }
comments powered by Disqus