AspectRatio
A utility component for declaratively matching a given aspect-ratio.
Effectively prevents Layout Shift by reserving space in advance.
Polymorphism
The AspectRatio component supports the as prop for polymorphism.
- By default, it wraps children in a
div, and theasprop allows changing the wrapper element tag (e.g., div → article). - The
aspect-ratioCSS property is applied to the wrapper element to reserve space.
Composition & Rendering Delegation
The AspectRatio component supports the Composition and Rendering Delegation patterns via the asChild prop.
- When
asChildistrue, it renders the child element directly via Slot. - The
aspect-ratioCSS property is applied directly to the child element.- Slot only accepts a single child element.
- If a component is passed as a child to Slot, it must support
forwardRefand spreadprops. Otherwise it will not work correctly. - When using the
asChildprop, please refer to the Slot documentation.
Code
Interface
typescript
interface AspectRatioProps {
children: JSX.Element;
ratio: number;
asChild?: boolean;
style?: CSSProperties;
className?: string;
}
typescript
const AspectRatio: PolyForwardComponent<"div", AspectRatioProps, React.ElementType>
Props
| Name | Type | Default | Description |
|---|---|---|---|
children | JSX.Element | - | Child element |
ratio | number | - | The aspect ratio value |
asChild | boolean | false | When true, renders the child element via Slot |
style | CSSProperties | - | Inline style |
className | string | - | CSS class name |
Usage
Basic Usage
- By default, wraps children in a
divand applies theaspect-ratioCSS property to reserve space.
typescript
import { AspectRatio } from '@modern-kit/react'
const Example = () => {
const imgUrl = 'https://github.com/user-attachments/assets/dd60ec12-afd7-44c9-bd6b-0069e16bf2c9';
return (
<div style={{ width: '500px' }}>
<AspectRatio ratio={427 / 640}>
<img src={imgUrl} />
</AspectRatio>
</div>
);
};
as Prop Usage
- The
asprop allows rendering with a specific element instead ofdiv, applyingaspect-ratioto that element to reserve space.
typescript
import { AspectRatio } from '@modern-kit/react'
const Example = () => {
const imgUrl = 'https://github.com/user-attachments/assets/dd60ec12-afd7-44c9-bd6b-0069e16bf2c9';
return (
<div style={{ width: '500px' }}>
<AspectRatio as="article" ratio={427 / 640}>
<img src={imgUrl} />
</AspectRatio>
</div>
);
};
asChild Prop Usage
- When
asChildistrue, it renders the child element as-is via Slot and appliesaspect-ratiodirectly to the child element.
typescript
import { AspectRatio } from '@modern-kit/react'
const Example = () => {
const imgUrl = 'https://github.com/user-attachments/assets/dd60ec12-afd7-44c9-bd6b-0069e16bf2c9';
return (
<div style={{ width: '500px' }}>
<AspectRatio asChild ratio={427 / 640}>
<img src={imgUrl} style={{ width: '100%' }} />
</AspectRatio>
</div>
);
};