saitolume / use-lazyload-ref

🖼️ Custom hook to use lazyload easily

Home Page:https://www.npmjs.com/package/use-lazyload-ref

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

use-lazyload-ref

GitHub license npm version CI Status

Custom hook to use lazyload easily

Installation

$ npm install use-lazyload-ref
$ yarn add use-lazyload-ref

Usage

To enable lazy loading, simply specify ref and data-src attributes.

import React from 'react'
import useLazyloadRef from 'use-lazyload-ref'

const Component = ({ url }) => {
  const [ref, hasLoaded] = useLazyloadRef()

  return (
    <div>
      {hasLoaded || <Skeleton />}
      <img ref={ref} data-src={url} />
      {/* <audio ref={ref} data-src={url} />*/}
      {/* <iframe ref={ref} data-src={url} />*/}
      {/* <video ref={ref} data-src={url} />*/}
      {/* <div style={{ backgroundImage: `url(${url})` }}></div>*/}
    </div>
  )
}

API

useLazyloadRef: () => [(node: HTMLElement | null) => void, boolean]

Custom hook. In addition to src in audio, iframe, img and video, CSS property background-image can be lazy loaded.

const [ref, hasLoaded] = useLazyloadRef()

useLazyloadRef returns a callback ref function and a load state.

  • ref: Initialize observer for lazyload.
  • hasLoaded: Default is false. Turn true if the source has finished loading.

License

MIT

About

🖼️ Custom hook to use lazyload easily

https://www.npmjs.com/package/use-lazyload-ref

License:MIT License


Languages

Language:TypeScript 100.0%