Package Exports
- ib-image-optimizer
- ib-image-optimizer/use-react
Readme
Image Optimizer
A React component for optimizing images with loading states and aspect ratio control.
Features
- ๐ผ๏ธ Image optimization with loading states
- ๐ Flexible aspect ratio control (auto, square, portrait, landscape)
- ๐ Customizable styling with Tailwind CSS
- ๐ Dark mode support
- ๐ Smooth fade-in transitions
- ๐ก๏ธ Error handling with fallback images
- ๐ฑ Responsive design
- โก TypeScript support
- ๐งช Test coverage with Jest and React Testing Library
Installation
npm install ib-image-optimizer
Usage
Basic Usage
import { ImageOptimizer } from "ib-image-optimizer";
function App() {
return (
<ImageOptimizer
src="https://example.com/image.jpg"
alt="Description"
aspectRatio="auto"
className="rounded-lg shadow-lg"
showSkeleton={true}
fallbackSrc="https://example.com/fallback.jpg"
onError={(error) => console.error(error)}
onLoad={() => console.log("Image loaded")}
/>
);
}
Props
Prop | Type | Default | Description |
---|---|---|---|
src |
string | - | The source URL of the image |
alt |
string | - | Alt text for the image |
aspectRatio |
"auto" | "square" | "portrait" | "landscape" | "auto" | The aspect ratio of the image |
className |
string | - | Additional CSS classes to apply |
style |
React.CSSProperties | - | Inline styles to apply |
showSkeleton |
boolean | true | Whether to show the loading skeleton |
fallbackSrc |
string | - | Fallback image URL if the main image fails to load |
onError |
(error: Error | ErrorEvent) => void | - | Error handler callback |
onLoad |
() => void | - | Load handler callback |
Aspect Ratios
The component supports multiple aspect ratios:
auto
: Natural aspect ratio of the imagesquare
: 1:1 aspect ratioportrait
: 3:4 aspect ratiolandscape
: 4:3 aspect ratio
Styling
You can customize the appearance using:
className
prop for Tailwind CSS classesstyle
prop for inline styles
Example:
<ImageOptimizer
src="image.jpg"
alt="Custom styled image"
className="rounded-full border-4 border-blue-500"
style={{ filter: "grayscale(50%)" }}
/>
Error Handling
The component provides robust error handling:
fallbackSrc
prop for a backup imageonError
callback for error handling- Automatic fallback to null if no fallback image is provided
Example:
<ImageOptimizer
src="https://invalid-url.com/image.jpg"
fallbackSrc="fallback.jpg"
onError={(error) => console.error("Image failed to load:", error)}
/>
Development
- Clone the repository
- Install dependencies:
npm install
- Start the development server:
npm run dev
- Run tests:
npm test
- Generate coverage report:
npm run test:coverage
Testing
The component includes comprehensive tests using Jest and React Testing Library. Key test cases include:
- Loading states
- Error handling
- Aspect ratio changes
- Fallback image behavior
- Event handling
Run the test suite:
npm test
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.