{"id":22808885,"url":"https://github.com/morganney/background-image-size-hook","last_synced_at":"2026-05-02T13:31:31.591Z","repository":{"id":46651037,"uuid":"412303865","full_name":"morganney/background-image-size-hook","owner":"morganney","description":"React hook to get the size in pixels of a CSS background image","archived":false,"fork":false,"pushed_at":"2021-10-01T15:56:06.000Z","size":137,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-09-15T17:15:42.044Z","etag":null,"topics":["background-image","hooks","pixels","react","size"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/morganney.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-10-01T02:52:58.000Z","updated_at":"2021-10-01T15:54:05.000Z","dependencies_parsed_at":"2022-08-29T21:20:31.495Z","dependency_job_id":null,"html_url":"https://github.com/morganney/background-image-size-hook","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/morganney/background-image-size-hook","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/morganney%2Fbackground-image-size-hook","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/morganney%2Fbackground-image-size-hook/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/morganney%2Fbackground-image-size-hook/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/morganney%2Fbackground-image-size-hook/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/morganney","download_url":"https://codeload.github.com/morganney/background-image-size-hook/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/morganney%2Fbackground-image-size-hook/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32536498,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-02T12:25:33.646Z","status":"ssl_error","status_checked_at":"2026-05-02T12:24:51.733Z","response_time":132,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["background-image","hooks","pixels","react","size"],"created_at":"2024-12-12T11:12:43.055Z","updated_at":"2026-05-02T13:31:31.552Z","avatar_url":"https://github.com/morganney.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# [`background-image-size-hook`](https://www.npmjs.com/package/background-image-size-hook)\n\n![CI](https://github.com/morganney/background-image-size-hook/actions/workflows/ci.yml/badge.svg)\n[![codecov](https://codecov.io/gh/morganney/background-image-size-hook/branch/master/graph/badge.svg?token=DYGZWNW556)](https://codecov.io/gh/morganney/background-image-size-hook)\n\nReact hook to get the size of CSS background images.\n\n## Usage\n\nFirst `npm i background-image-size-hook react react-dom`.\n\nThen when you want to change the dimensions of an element based on the size of its loaded background image:\n\n```js\nimport { useBackgroundImageSize } from 'background-image-size-hook'\nimport styled from 'styled-components'\n\nconst Box = styled.div`\n  background-image: url('https://other-domain.com/images/cool.png');\n  width: ${({ image }) =\u003e image.width}px;\n  height: ${({ image }) =\u003e image.height}px;\n`\n\nconst App = () =\u003e {\n  const [ref, image] = useBackgroundImageSize()\n  // Use a default while the background image is asynchronously re-loading\n  const defaultSize = { width: 200, height: 200 }\n\n  return \u003cBox ref={ref} image={image ?? defaultSize} /\u003e\n}\n```\n\nAlternatively, you can hide the element with CSS until the background-image size is known:\n\n```js\nconst Box = styled.div`\n  background-image: url('https://other-domain.com/images/cool.png');\n  display: ${({ image }) =\u003e image ? 'block' : 'none'};\n  width: ${({ image }) =\u003e image?.width ?? 200}px;\n  height: ${({ image }) =\u003e image?.height ?? 200}px;\n`\n\nconst App = () =\u003e {\n  const [ref, image] = useBackgroundImageSize()\n\n  return (\n    \u003c\u003e\n      \u003cBox ref={ref} image={image} /\u003e\n      {!image \u0026\u0026 \u003cSkeleton width=\"200px\" height=\"200px\" /\u003e}\n    \u003c/\u003e\n  )\n}\n```\n\n## Advanced Usage\n\nBeyond the simple use case of one static background image, more complex use cases require different hook behavior.\n\n### Multiple Background Images\n\nIf 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:\n\n```js\nconst Box = styled.div`\n  background-image:\n    linear-gradient(rgba(0, 0, 255, 0.5), rgba(255, 255, 0, 0.5)),\n    url('https://other-domain.com/images/cool.png'),\n    url('data:image/png;base64,iRxVB0…');\n`\nconst App = () =\u003e {\n  const [ref, images] = useBackgroundImageSize()\n\n  console.log(images) // Array of two objects for each background image (once loaded)\n\n  return \u003cBox ref={ref} /\u003e\n}\n```\n\n### Dynamic Background Images\n\nIf you use dynamic imports to load background images, for instance gravatars or tenant logos, and use a JavaScript bundler that supports loaders like [webpack](https://webpack.js.org/loaders/) or [esbuild](https://esbuild.github.io/api/#loader), 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](#multiple-dependencies) approach explained below by having the dynamic import state (`logo`) as a dependency.\n\n```js\nconst Box = styled.div`\n  display: ${({ image }) =\u003e (image ? 'block' : 'none')};\n  background-image: url('${({ image }) =\u003e image?.src}');\n  width: ${({ image }) =\u003e image?.width ?? 200}px;\n  height: ${({ image }) =\u003e image?.height ?? 100}px;\n`\n\nconst App = () =\u003e {\n  const { tenantId } = useContext(Context)\n  const [logo, setLogo] = useState('')\n  const [ref, image] = useBackgroundImageSize(logo)\n\n  useEffect(() =\u003e {\n    const fetchTenantLogo = async () =\u003e {\n      try {\n        const logoImport = await import(`./assets/${tenantId}/logo.png`)\n\n        setLogo(logoImport.default)\n      } catch {\n        setLogo('defaultLogo.svg')\n      }\n    }\n\n    fetchTenantLogo()\n  }, [tenantId])\n\n  return (\n    \u003c\u003e\n      \u003cBox ref={ref} image={image} /\u003e\n      {!image \u0026\u0026 \u003cSkeleton width=\"200px\" height=\"100px\" /\u003e}\n    \u003c/\u003e\n  )\n}\n```\n\nIf 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:\n\n```js\n  const urls = useMemo(() =\u003e [urlA, urlB], [urlA, urlB])\n  const [ref, images] = useBackgroundImageSize(urls)\n```\n\n### Multiple Dependencies\n\nIf 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.\n\n```js\nconst App = () =\u003e {\n  const [ref, images, getImageSizes] = useBackgroundImageSize(true)\n\n  useEffect(() =\u003e {\n    getImageSizes()\n  }, [getImageSizes, dep1, dep2, etc])\n\n  return \u003cBox ref={ref} images={images} /\u003e\n}\n```\n\n## About the Ref\n\nTo 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.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmorganney%2Fbackground-image-size-hook","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmorganney%2Fbackground-image-size-hook","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmorganney%2Fbackground-image-size-hook/lists"}