To use react-blurhash without knowing the exact width and height of the placeholder, you can dynamically calculate the dimensions based on the container size or use CSS to make the placeholder responsive. Here's how:
Steps to Use react-blurhash Without Exact Dimensions
Install react-blurhash:
Install the library: npm install react-blurhash.
Use a Container with Dynamic Dimensions:
Wrap the Blurhash component in a container (e.g., div) and use CSS to make it responsive.
Calculate Dimensions Dynamically:
Use a ref or ResizeObserver to get the container's dimensions and pass them to the Blurhash component.
Example Code
import React, { useRef, useState, useEffect } from "react";
import { Blurhash } from "react-blurhash";
const BlurhashPlaceholder = ({ hash }) => {
const containerRef = useRef(null);
const [dimensions, setDimensions] = useState({ width: 0, height: 0 });
useEffect(() => {
const updateDimensions = () => {
if (containerRef.current) {
const { width, height } = containerRef.current.getBoundingClientRect();
setDimensions({ width, height });
}
};
// Update dimensions on mount and window resize
updateDimensions();
window.addEventListener("resize", updateDimensions);
// Cleanup
return () => window.removeEventListener("resize", updateDimensions);
}, []);
return (
<div
ref={containerRef}
style={{ width: "100%", height: "100%", position: "relative" }}
>
<Blurhash
hash={hash}
width={dimensions.width}
height={dimensions.height}
resolutionX={32}
resolutionY={32}
punch={1}
/>
</div>
);
};
export default BlurhashPlaceholder;