react-packages

@react-packages/rect

It’s React component to render a flex box that keeps the aspect ratio between its height and width even when it’s resized. For example:

import Rect from '@react-packages/rect';

const containerStyle = {
    borderStyle: 'solid',
    borderWidth: '1px',
    flex: 1,
    paddingInline: '8px',
    paddingBlock: '4px',
};
const itemStyle = {
    borderStyle: 'solid',
    borderWidth: '1px',
    flex: 1,
    paddingInline: '8px',
    paddingBlock: '4px',
};

...

<div style={containerStyle}>
    <Rect style={itemStyle} />
    <Rect style={itemStyle} />
    <Rect style={itemStyle} />
</div>

The JSX code part above will render three square boxes (height and width have ratio 1:1). If we want different ratio, we can define ratioX and/or ratioY prop.

Rect component works well if
className and/or style props produce only one side (height/width) which has the length greater than 0 (excluding border and padding) and another side has zero length (excluding border and padding). By default, Rect is a block element. The zero length side will be recalculated based on another side so that the ratio between sides is fulfilled.

The usage

For example, we want to render an image centered inside a box. We can use the following example:

import Rect, {styles} from '@react-packages/rect';

...

<Rect ...>
    <img ...
        style={styles.centeredImage}
    />
</Rect>

where styles.centeredImage is {height:'100%', objectFit:'contain', objectPosition:'center', width:'100%'}.

The previous example can be replaced by FlexImage component which is included in this package.

Rect component props

All props are optional.