A simple (and hopefully useful) react component to render your images keeping their aspect ratio.
npm i react-picture-ratio
🇧🇷 Português do Brasil | 🇺🇸 English
This component was built in order to solve two main problems:
You may have already had the expecrience of accessing a site, it is not fully loaded, you scroll the content when suddenly... "skips" an image on the screen and pushes the content you were viewing or were about to click. Well, this type of behavior is measured by Core Web Vitals with the Cumulative Layout Shift metric.
The Aspect Ratio is nothing more than the proportion of a given content relating its dimensions of width and height (the image below illustrates this well). Our react-picture-ratio
component will keep the proportion that is passed but adapting to the layout.
Source: https://clipchamp.com/en/blog/what-aspect-ratio/
<Picture />
: use the Picture component as if it were an image tag.
props | type | required | default | description |
---|---|---|---|---|
aspectRatio | string | false | 4:3 | width x height ratio you want your image to be |
className | string | false | - | Custom name of class attribute for component wrap |
src | string | true | - | URL of an image |
alt | string | true | - | Alternative text for the image if it doesn't load |
<Picture />
inherits all properties from ImgHTMLAttributes
import React from 'react';
import { Picture } from 'react-picture-ratio';
function App() {
return (
<div className="App">
<Picture
aspectRatio="450:300" // or "450/300"
src="https://via.placeholder.com/450x300"
alt="Image with width of 450px and height of 300px"
/>
</div>
);
}
Two ways:
-
- Install
react-picture
directly from npm to use in your proeject.
- Install
- 2ª Install the entire current repository and contribute to it.
yarn add react-picture-ratio
# or
npm i react-picture-ratio
- Fork the project
# Clone the repository
git clone https://github.com/{seu_usuario}/react-picture-ratio.git
cd react-picture-ratio
# Install dependencies
yarn install
# Create a new branch for your changes
git checkout -b nova_branch
# After addingg your changes run the tests
yarn test
This project is under the MIT license.
Ari Jesus |