React resize image
React component for resizing image on the fly with RSZ.io.
RSZ.IO is a free image resizing proxy that can resize images, change image formats and optimize images for your website.
Motivation
My website is slow because of my image is so big. And then i use rsz.io for resizing all of my in my website images. The result is it becomes so fast as lightning. So, why not make react components for wrapping images to be fast with rsz.io ?
Development
I use https://github.com/damaera/publish-react-component Boilerplate for publishing react component to npm, With testing and storybook.
here is the folder structure
The core of this component is just manipulating link with rsz.io. you can look at the code at /src/getRSZioUrl
. With regex it check link at first, and then if it's link it's insert rsz.io before hostname and adding params if options available.
const getRSZioUrl = (src, options) => {
let result = src
// if is link
if (/^https?:\/\//.test(src)) {
result = result.replace(/^(https?:\/\/)/, '$1rsz.io/')
if (options) {
result += '?' + objectToParams(options)
}
}
return result/* */
}
Then wrap it to img components
const ResizeImage = (props) => {
const { src, options, style, alt, resizeActive } = props
return (
<img
src={resizeActive ? getRSZioUrl(src, options) : src}
alt={alt}
style={style}
/>
)
}
Finally you can try the result here
Install
yarn add react-resize-image
Usage
import React, { Component } from 'react'
import ResizeImage from 'react-resize-image'
class componentName extends Component {
render () {
return (
<ResizeImage
src={src}
alt="Tsunami bt hokusai"
options={{ width: 200 }}
/>
)
}
}
export default componentName
Props
List of props components
Props | Desc |
---|---|
src | required image source, must be absolute path from http or https |
alt | required image alt |
resizeActive | optional for enabling or disabling resizer. For example if you using your localhost or local development environment, you should disable it. |
options | optional RSZ.io options, for more options please visit http://rsz.io/ |
style | optional component style |
Here is the demo
Future
In the future it will add lazyload and animation feature
Contributing
Github: https://github.com/damaera/react-resize-image
You can fork the project, and install it locally. Then use this styleguide for contributing. https://github.com/airbnb/javascript/tree/master/react
Posted on Utopian.io - Rewarding Open Source Contributors