npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

background-image-size-hook

v1.0.1

Published

React hook to get the size of a CSS background-image

Downloads

5

Readme

background-image-size-hook

CI codecov

React hook to get the size of CSS background images.

Usage

First npm i background-image-size-hook react react-dom.

Then when you want to change the dimensions of an element based on the size of its loaded background image:

import { useBackgroundImageSize } from 'background-image-size-hook'
import styled from 'styled-components'

const Box = styled.div`
  background-image: url('https://other-domain.com/images/cool.png');
  width: ${({ image }) => image.width}px;
  height: ${({ image }) => image.height}px;
`

const App = () => {
  const [ref, image] = useBackgroundImageSize()
  // Use a default while the background image is asynchronously re-loading
  const defaultSize = { width: 200, height: 200 }

  return <Box ref={ref} image={image ?? defaultSize} />
}

Alternatively, you can hide the element with CSS until the background-image size is known:

const Box = styled.div`
  background-image: url('https://other-domain.com/images/cool.png');
  display: ${({ image }) => image ? 'block' : 'none'};
  width: ${({ image }) => image?.width ?? 200}px;
  height: ${({ image }) => image?.height ?? 200}px;
`

const App = () => {
  const [ref, image] = useBackgroundImageSize()

  return (
    <>
      <Box ref={ref} image={image} />
      {!image && <Skeleton width="200px" height="200px" />}
    </>
  )
}

Advanced Usage

Beyond the simple use case of one static background image, more complex use cases require different hook behavior.

Multiple Background Images

If the element has multiple background images then an array of objects will be returned instead of an object. Background images not referenced by a url will be ignored:

const Box = styled.div`
  background-image:
    linear-gradient(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5)),
    url('https://other-domain.com/images/cool.png'),
    url('data:image/png;base64,iRxVB0…');
`
const App = () => {
  const [ref, images] = useBackgroundImageSize()

  console.log(images) // Array of two objects for each background image (once loaded)

  return <Box ref={ref} />
}

Dynamic Background Images

If you use dynamic imports to load background images, for instance gravatars or tenant logos, and use a JavaScript bundler that supports loaders like webpack or esbuild, then you can pass the resolved urls from the imports to the hook, so that the calculation of the background image size is dependent upon changes to the resolved url. This can also be achieved with the mutliple dependencies approach explained below by having the dynamic import state (logo) as a dependency.

const Box = styled.div`
  display: ${({ image }) => (image ? 'block' : 'none')};
  background-image: url('${({ image }) => image?.src}');
  width: ${({ image }) => image?.width ?? 200}px;
  height: ${({ image }) => image?.height ?? 100}px;
`

const App = () => {
  const { tenantId } = useContext(Context)
  const [logo, setLogo] = useState('')
  const [ref, image] = useBackgroundImageSize(logo)

  useEffect(() => {
    const fetchTenantLogo = async () => {
      try {
        const logoImport = await import(`./assets/${tenantId}/logo.png`)

        setLogo(logoImport.default)
      } catch {
        setLogo('defaultLogo.svg')
      }
    }

    fetchTenantLogo()
  }, [tenantId])

  return (
    <>
      <Box ref={ref} image={image} />
      {!image && <Skeleton width="200px" height="100px" />}
    </>
  )
}

If you want to pass urls from multiple dynamic background images, then use an array but make sure its reference does not change across renders, i.e. it is memoized:

  const urls = useMemo(() => [urlA, urlB], [urlA, urlB])
  const [ref, images] = useBackgroundImageSize(urls)

Multiple Dependencies

If you want to control when the background image size is computed based on other dependencies you can get a reference to the hook's callback by passing true. In this case the hook will return a callback function that can be called when one of the dependencies changes to get the background image size.

const App = () => {
  const [ref, images, getImageSizes] = useBackgroundImageSize(true)

  useEffect(() => {
    getImageSizes()
  }, [getImageSizes, dep1, dep2, etc])

  return <Box ref={ref} images={images} />
}

About the Ref

To determine the exact width and height in pixels of the background image, it is reloaded into a dynamic image element (not attached to any DOM tree) which is an asynchronous process. Therefore, in all use cases you must attach the ref to the element with the background image to help prevent memory leaks, i.e. prevent the hook from potentially calling setState on an unmounted component. When no URLs are passed to the hook, the ref is used to get the URL of the background image, in addition to helping prevent a memory leaks.