Repository: vivaxy/react-native-auto-height-image
Branch: master
Commit: 0bb6a33e5cf3
Files: 34
Total size: 32.0 KB
Directory structure:
gitextract_dhxmzn1f/
├── .editorconfig
├── .github/
│ ├── FUNDING.yml
│ └── ISSUE_TEMPLATE/
│ ├── bug_report.md
│ └── feature_request.md
├── .gitignore
├── .husky/
│ ├── .gitignore
│ ├── commit-msg
│ └── pre-commit
├── .npmignore
├── .npmrc
├── .prettierignore
├── .yarnrc
├── AnimatableImage.js
├── AutoHeightImage.js
├── CHANGELOG.md
├── CITATION.cff
├── CONTRIBUTING.md
├── ErrorableImage.js
├── ExampleApp/
│ ├── .expo-shared/
│ │ └── assets.json
│ ├── .gitignore
│ ├── .watchmanconfig
│ ├── App.js
│ ├── app.json
│ ├── babel.config.js
│ └── package.json
├── ImagePolyfill.js
├── LICENSE
├── README.md
├── cache.js
├── helpers.js
├── index.d.ts
├── index.js
├── package.json
└── renovate.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
curly_bracket_next_line = false
spaces_around_operators = true
indent_brace_style = 1tbs
[*.js]
quote_type = single
[*.{html,less,css,json}]
quote_type = double
================================================
FILE: .github/FUNDING.yml
================================================
patreon: vivaxy
open_collective: react-native-auto-height-image
custom: ['https://gist.github.com/vivaxy/58eed1803a2eddda05c90aed99430de2']
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Codes:
```js
....
```
2. Click on '....'
3. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Dependencies versions (please complete the following information):**
- react:
- react-native:
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .gitignore
================================================
.idea
.DS_Store
/build
node_modules
npm-debug.log
yarn-error.log
================================================
FILE: .husky/.gitignore
================================================
_
================================================
FILE: .husky/commit-msg
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn commitlint --edit $1
================================================
FILE: .husky/pre-commit
================================================
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
yarn lint-staged
================================================
FILE: .npmignore
================================================
.idea
node_modules
.DS_Store
npm-debug.log
.editorconfig
/ExampleApp
================================================
FILE: .npmrc
================================================
registry=https://registry.npmjs.org/
================================================
FILE: .prettierignore
================================================
CHANGELOG.md
README.md
package.json
ExampleApp/app.json
================================================
FILE: .yarnrc
================================================
--registry "https://registry.npmjs.org/"
================================================
FILE: AnimatableImage.js
================================================
import React from 'react';
import PropTypes from 'prop-types';
import { Animated, Image, ImageBackground } from 'react-native';
function AnimatableImage(props) {
const { animated, children, ...rest } = props;
const ImageComponent = children
? ImageBackground
: animated
? Animated.Image
: Image;
return {children};
}
AnimatableImage.propTypes = Image.propTypes | Animated.Image.propTypes;
AnimatableImage.defaultProps = {
animated: false
};
export default AnimatableImage;
================================================
FILE: AutoHeightImage.js
================================================
/**
* @since 2017-04-11 19:10:08
* @author vivaxy
*/
import React, { useEffect, useState, useRef } from 'react';
import ImagePolyfill from './ImagePolyfill';
import AnimatableImage from './AnimatableImage';
import PropTypes from 'prop-types';
import { getImageSizeFitWidth, getImageSizeFitWidthFromCache } from './cache';
import { NOOP, DEFAULT_HEIGHT } from './helpers';
// remove `resizeMode` props from `Image.propTypes`
const { resizeMode, ...ImagePropTypes } = AnimatableImage.propTypes;
function AutoHeightImage(props) {
const {
onHeightChange,
source,
width,
style,
maxHeight,
onError,
...rest
} = props;
const [height, setHeight] = useState(
getImageSizeFitWidthFromCache(source, width, maxHeight).height ||
DEFAULT_HEIGHT
);
const mountedRef = useRef(false);
useEffect(function () {
mountedRef.current = true;
return function () {
mountedRef.current = false;
};
}, []);
useEffect(
function () {
(async function () {
try {
const { height: newHeight } = await getImageSizeFitWidth(
source,
width,
maxHeight
);
if (mountedRef.current) {
// might trigger `onHeightChange` with same `height` value
// dedupe maybe?
setHeight(newHeight);
onHeightChange(newHeight);
}
} catch (e) {
onError(e);
}
})();
},
[source, onHeightChange, width, maxHeight]
);
// StyleSheet.create will cache styles, not what we want
const imageStyles = { width, height };
// Since it only makes sense to use polyfill with remote images
const ImageComponent = source.uri ? ImagePolyfill : AnimatableImage;
return (
);
}
AutoHeightImage.propTypes = {
...ImagePropTypes,
width: PropTypes.number.isRequired,
maxHeight: PropTypes.number,
onHeightChange: PropTypes.func,
animated: PropTypes.bool
};
AutoHeightImage.defaultProps = {
maxHeight: Infinity,
onHeightChange: NOOP,
animated: false
};
export default AutoHeightImage;
================================================
FILE: CHANGELOG.md
================================================
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
### [3.2.4](https://github.com/vivaxy/react-native-auto-height-image/compare/v3.2.3...v3.2.4) (2021-02-04)
### Features
* supports `ImageBackground` [@SoniaComp](https://github.com/SoniaComp)
### [3.2.3](https://github.com/vivaxy/react-native-auto-height-image/compare/v3.2.2...v3.2.3) (2020-10-17)
### Bug Fixes
* **deps:** update dependency expo to v39 ([9cf60e4](https://github.com/vivaxy/react-native-auto-height-image/commit/9cf60e4798742a4ef648cc39cd96af6380b7180e))
* **deps:** update dependency react to v16.14.0 ([ed45e7e](https://github.com/vivaxy/react-native-auto-height-image/commit/ed45e7ebf50b677ccdc501a01ae813258660cfc6))
* **deps:** update dependency react-native-web to ^0.14.0 ([1ad617f](https://github.com/vivaxy/react-native-auto-height-image/commit/1ad617fa514cb307fc72a3c34e8254843e19d9d0))
### [3.2.2](https://github.com/vivaxy/react-native-auto-height-image/compare/v3.2.1...v3.2.2) (2020-07-25)
### Bug Fixes
* **deps:** update dependency expo to v38 ([6b24bd8](https://github.com/vivaxy/react-native-auto-height-image/commit/6b24bd8c1a2f1bf7fafcb0ba3c7b558318d7d152))
* **deps:** update dependency react-native-web to ^0.13.0 ([82d6270](https://github.com/vivaxy/react-native-auto-height-image/commit/82d6270e7e45855864fcc4fcf1ec62ee97695300))
### [3.2.1](https://github.com/vivaxy/react-native-auto-height-image/compare/v3.2.0...v3.2.1) (2020-06-08)
## [3.2.0](https://github.com/vivaxy/react-native-auto-height-image/compare/v3.1.3...v3.2.0) (2020-05-27)
### Features
* :sparkles: support `maxHeight` prop, reuse image cache on initial rendering to optimize the performance ([e5055c8](https://github.com/vivaxy/react-native-auto-height-image/commit/e5055c8e97a800581d7049140392cdedad035f48))
### [3.1.3](https://github.com/vivaxy/react-native-auto-height-image/compare/v3.1.2...v3.1.3) (2020-05-07)
### Bug Fixes
* :bug: fix `Can't perform a React state update on an unmounted component.` ([035e6a8](https://github.com/vivaxy/react-native-auto-height-image/commit/035e6a86ba39daf3c16d75d7467f925d94537023)), closes [#44](https://github.com/vivaxy/react-native-auto-height-image/issues/44)
### [3.1.2](https://github.com/vivaxy/react-native-auto-height-image/compare/v3.1.1...v3.1.2) (2020-04-18)
### Bug Fixes
* add missing symbol ([7498b82](https://github.com/vivaxy/react-native-auto-height-image/commit/7498b823bb8ac8a0f1f509fb0f083a61e57e192d))
### [3.1.1](https://github.com/vivaxy/react-native-auto-height-image/compare/v3.1.0...v3.1.1) (2020-04-04)
### Bug Fixes
* android crash at imagePolyfill ([21dc084](https://github.com/vivaxy/react-native-auto-height-image/commit/21dc0841c452a4178202db1beedfc7e2e72d7665))
## [3.1.0](https://github.com/vivaxy/react-native-auto-height-image/compare/v3.0.0...v3.1.0) (2020-03-31)
### Features
* animated image support ([97ff786](https://github.com/vivaxy/react-native-auto-height-image/commit/97ff786c40143599228524c1b12d4e29ba496e57))
## [3.0.0](https://github.com/vivaxy/react-native-auto-height-image/compare/v2.0.0...v3.0.0) (2020-01-17)
### ⚠ BREAKING CHANGES
* **changelog:** Drop support for react before 16.8 and react-native before 0.59
* **changelog:** :memo: commit a breaking change ([03c9b81](https://github.com/vivaxy/react-native-auto-height-image/commit/03c9b81))
### Bug Fixes
* fix for fallback images ([d825375](https://github.com/vivaxy/react-native-auto-height-image/commit/d825375))
### Features
* **deps:** bumped React to ^16.8 & React Native to ^0.59.0 ([24edbc2](https://github.com/vivaxy/react-native-auto-height-image/commit/24edbc2))
## [2.0.0](https://github.com/vivaxy/react-native-auto-height-image/compare/v1.1.3...v2.0.0) (2020-01-09)
### ⚠ BREAKING CHANGES
* incorporated imagepolyfill in codebase, removed from deps
### Features
* incorporated imagepolyfill in codebase, removed from deps ([bfdca6f](https://github.com/vivaxy/react-native-auto-height-image/commit/bfdca6f))
## [1.1.3](https://github.com/vivaxy/react-native-auto-height-image/compare/v1.1.2...v1.1.3) (2019-10-16)
## [1.1.1](https://github.com/vivaxy/react-native-auto-height-image/compare/v1.1.0...v1.1.1) (2019-08-13)
### Reverts
* **open collective:** :rewind: revert changes to package.json ([37f3b17](https://github.com/vivaxy/react-native-auto-height-image/commit/37f3b17))
# [1.1.0](https://github.com/vivaxy/react-native-auto-height-image/compare/v1.0.5...v1.1.0) (2019-03-07)
### Features
* :sparkles:updateImageHeight with safe check ([a2c9275](https://github.com/vivaxy/react-native-auto-height-image/commit/a2c9275))
## [1.0.5](https://github.com/vivaxy/react-native-auto-height-image/compare/v1.0.4...v1.0.5) (2018-10-22)
### Bug Fixes
* :bug:Fix updating the image size after change of the source ([cfe1566](https://github.com/vivaxy/react-native-auto-height-image/commit/cfe1566))
## [1.0.4](https://github.com/vivaxy/react-native-auto-height-image/compare/v1.0.3...v1.0.4) (2018-10-09)
### Bug Fixes
* :bug:Remove trailing comma ([89713a5](https://github.com/vivaxy/react-native-auto-height-image/commit/89713a5))
## [1.0.3](https://github.com/vivaxy/react-native-auto-height-image/compare/v1.0.2...v1.0.3) (2018-10-09)
### Features
* Allowing Image props.
## [1.0.2](https://github.com/vivaxy/react-native-auto-height-image/compare/v1.0.1...v1.0.2) (2018-10-07)
### Features
* Add type definitions.
## [1.0.1](https://github.com/vivaxy/react-native-auto-height-image/compare/v1.0.0...v1.0.1) (2018-07-13)
### Features
* Reformat codes.
# [1.0.0](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.4.0...v1.0.0) (2018-01-18)
### Features
* Support local images and fallback sources.
### Breaking changes.
* Remove `imageURL`, use `source` instead.
# [0.4.0](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.3.4...v0.4.0) (2018-01-16)
### Features
* **onError:** :sparkles:Propagate errors to onError ([4d9a14d](https://github.com/vivaxy/react-native-auto-height-image/commit/4d9a14d))
## [0.3.4](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.3.3...v0.3.4) (2017-12-20)
### Features
* Update image size on width change. ([7a09dc0](https://github.com/vivaxy/react-native-auto-height-image/commit/7a09dc0))
## [0.3.3](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.3.2...v0.3.3) (2017-08-22)
### Features
* Optimize error handling from `Image.getSize`. ([80158e7](https://github.com/vivaxy/react-native-auto-height-image/commit/80158e7))
## [0.3.2](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.3.1...v0.3.2) (2017-08-22)
### Bug Fixes
* **rejection:** :bug:Fix `Possible Unhandled Promise Rejection` warning. ([02441ba](https://github.com/vivaxy/react-native-auto-height-image/commit/02441ba)), closes [#4](https://github.com/vivaxy/react-native-auto-height-image/issues/4)
## [0.3.1](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.3.0...v0.3.1) (2017-08-08)
### Bug Fixes
* :bug:Fixed syntax error in index.js. ([c384cd6](https://github.com/vivaxy/react-native-auto-height-image/commit/c384cd6))
# [0.3.0](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.2.2...v0.3.0) (2017-07-31)
### Features
* **onHeightChange:** :sparkles:Provides a new api to extract the calculated height. ([18c86e6](https://github.com/vivaxy/react-native-auto-height-image/commit/18c86e6))
## [0.2.2](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.2.1...v0.2.2) (2017-05-27)
### Documents
* Update documents.
## [0.2.1](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.2.0...v0.2.1) (2017-04-24)
### Bug Fixes
* :bug:Fix hasLoaded logic ([1b8264c](https://github.com/vivaxy/react-native-auto-height-image/commit/1b8264c))
# [0.2.0](https://github.com/vivaxy/react-native-auto-height-image/compare/v0.1.0...v0.2.0) (2017-04-24)
### Features
* :sparkles:Support all image props ([4088b73](https://github.com/vivaxy/react-native-auto-height-image/commit/4088b73))
# 0.1.0 (2017-04-24)
### Features
* :tada:First Commit ([243c394](https://github.com/vivaxy/react-native-auto-height-image/commit/243c394))
================================================
FILE: CITATION.cff
================================================
cff-version: 1.1.0
message: "If you use this software, please cite it as below."
authors:
- family-names: Xu
given-names: Ye
orcid: https://doi.org/10.5281/zenodo.7813210
title: vivaxy/react-native-auto-height-image
version: v3.2.4
date-released: 2023-04-10
================================================
FILE: CONTRIBUTING.md
================================================
# How to initialize project?
* Clone this repository.
* Run `yarn install`. (Install `yarn` globally.)
* Make sure you have `watchman` installed. (If not, run `brew install watchman`.)
# How to run ExampleApp?
* Run `cd ExampleApp`.
* Run `yarn install`.
* Run `yarn start`.
# How to make a change?
* Supply a proper test case and test your changes in ExampleApp.
* Git commit with [Conventional Commits](https://conventionalcommits.org/).
* Bump version and publish with `npm run release`. This will update `CHANGELOG.md` automatically.
# How to release a beta/test version?
* Run `yarn release:beta`.
# How to release a stable version?
* Run `yarn release`.
================================================
FILE: ErrorableImage.js
================================================
import React, { useState } from 'react';
import AutoHeightImage from './AutoHeightImage';
function ErrorableImage(props) {
const { source, fallbackSource, onError, ...rest } = props;
const [error, setError] = useState(false);
const shouldUseFallbackSource = error && fallbackSource;
return (
{
// if an error hasn't already been seen, try to load the error image
// instead
if (!error) {
setError(true);
}
// also propagate to error handler if it is specified
onError && onError(_e);
}}
{...rest}
/>
);
}
export default ErrorableImage;
================================================
FILE: ExampleApp/.expo-shared/assets.json
================================================
{
"f9155ac790fd02fadcdeca367b02581c04a353aa6d5aa84409a59f6804c87acd": true,
"89ed26367cdb9b771858e026f2eb95bfdb90e5ae943e716575327ec325f39c44": true
}
================================================
FILE: ExampleApp/.gitignore
================================================
node_modules/**/*
.expo/*
npm-debug.*
*.jks
*.p8
*.p12
*.key
*.mobileprovision
*.orig.*
web-build/
web-report/
================================================
FILE: ExampleApp/.watchmanconfig
================================================
{}
================================================
FILE: ExampleApp/App.js
================================================
import React, { Component } from 'react';
import AutoHeightImage from 'react-native-auto-height-image';
import {
StyleSheet,
Text,
ScrollView,
TextInput,
Animated
} from 'react-native';
import image from './assets/image.png';
export default class App extends Component {
state = {
dynamicWidth: 200,
fadeAnim: new Animated.Value(0)
};
handleTextInputChange = (text) => {
const width = Number(text);
if (!Number.isNaN(width)) {
this.setState({ dynamicWidth: width });
}
};
fadeIn = () => {
Animated.timing(this.state.fadeAnim, {
toValue: 1,
duration: 5000,
useNativeDriver: true
}).start();
};
componentDidMount() {
this.fadeIn();
}
render() {
const { dynamicWidth } = this.state;
return (
Basic example
Basic example with local image
Basic example with dynamic width
Basic example with dynamic width and local image
Wrong image
{
console.log('----- onError', error);
}}
/>
Wrong image with fallback
{
console.log('----- onError', error);
}}
/>
Wrong image with local fallback
{
console.log('----- onError', error);
}}
/>
AnimatableImage
ImageBackground
You can make any Child Component!
);
}
}
const styles = StyleSheet.create({
scrollViewContainer: {
flex: 1,
backgroundColor: '#fff',
marginTop: 20
},
scrollViewContentContainer: {
alignItems: 'center',
paddingTop: 100
},
textInputStyle: {
width: 300,
height: 30,
borderStyle: 'solid',
borderColor: '#eee',
borderWidth: 1
},
fadingContainer: {
paddingVertical: 8,
paddingHorizontal: 16,
backgroundColor: 'powderblue'
},
textStyle: {
color: 'white'
}
});
================================================
FILE: ExampleApp/app.json
================================================
{
"expo": {
"name": "ExampleApp for react-native-auto-height-image component",
"slug": "example-app-for-react-native-auto-height-image-component",
"privacy": "public",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"splash": {
"image": "./assets/splash.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"updates": {
"fallbackToCacheTimeout": 0
},
"assetBundlePatterns": [
"**/*"
],
"ios": {
"supportsTablet": true
},
"description": "ExampleApp for react-native-auto-height-image component",
"githubUrl": "https://github.com/vivaxy/react-native-auto-height-image/tree/master/ExampleApp"
}
}
================================================
FILE: ExampleApp/babel.config.js
================================================
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo']
};
};
================================================
FILE: ExampleApp/package.json
================================================
{
"main": "node_modules/expo/AppEntry.js",
"scripts": {
"start": "expo start",
"android": "expo start --android",
"ios": "expo start --ios",
"web": "expo start --web",
"eject": "expo eject",
"postinstall": "rm -rf ./node_modules/react-native-auto-height-image/node_modules && rm -rf ./node_modules/react-native-auto-height-image/ExampleApp"
},
"dependencies": {
"expo": "~41.0.0",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-native": "https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz",
"react-native-auto-height-image": "file:..",
"react-native-web": "~0.16.0"
},
"devDependencies": {
"babel-preset-expo": "^8.0.0"
},
"private": true
}
================================================
FILE: ImagePolyfill.js
================================================
import React, { useEffect } from 'react';
import { Platform, Image } from 'react-native';
import AnimatableImage from './AnimatableImage';
const isAndroid = () => Platform.OS === 'android';
/**
* An extension of the Image class which fixes an Android bug where remote images wouldn't fire the
* Image#onError() callback when the image failed to load due to a 404 response.
*
* This component should only be used for loading remote images, not local resources.
*/
function ImagePolyfill(props) {
const { source, onError, ...rest } = props;
const verifyImage = () => {
const { uri } = source;
Image.prefetch(uri).catch((e) => onError(e));
};
useEffect(() => {
if (source && source.uri && onError && isAndroid()) {
verifyImage();
}
}, [source, onError]);
return ;
}
ImagePolyfill.propTypes = AnimatableImage.propTypes;
ImagePolyfill.defaultProps = AnimatableImage.defaultProps;
export default ImagePolyfill;
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2017 vivaxy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# react-native-auto-height-image
Initialized by [vivaxy/gt-npm-package](https://github.com/vivaxy/gt-npm-package)
[](https://www.npmjs.com/package/react-native-auto-height-image)
[](https://www.npmjs.com/package/react-native-auto-height-image)
[](./LICENSE)
[](https://conventionalcommits.org)
[](https://opencollective.com/react-native-auto-height-image)
[](https://github.com/vivaxy/react-native-auto-height-image/issues/88)
[](https://zenodo.org/badge/latestdoi/89235823)
This component provides you a simple way to load a remote image and automatically set `Image` height to the image dimension which fits the provided width.
React Native `Image` component needs users to set both `width` and `height` props.
React Native version requirements: >=0.46.
## Installation
`yarn add react-native-auto-height-image`
`npm install react-native-auto-height-image`
## Usage
Use local or remote files:
```js
import React, { Component } from 'react';
import AutoHeightImage from 'react-native-auto-height-image';
import image from 'gallifrey-falls.png';
export default class Demo extends Component {
render() {
return (
);
}
}
```
You can even specify fallback images for when the source fails to load:
```js
import React, { Component } from 'react';
import AutoHeightImage from 'react-native-auto-height-image';
import image from 'gallifrey-falls.png';
export default class Demo extends Component {
render() {
return (
);
}
}
```
### Props
| name | type | isRequired | default | description |
| --- | --- | --- | --- | --- |
| `width` | number | ✔ | N/A | image width to fit |
| `maxHeight` | number | ✖ | `Infinity` | image max height |
| `source` | number or object | ✔ | N/A | local (i.e. require/import) or remote image ({uri: '...'}) |
| `fallbackSource` | number or object | ✖ | N/A | local (i.e. require/import) or remote image ({uri: '...'}) |
| `onHeightChange` | func | ✖ | `(height) => {}` | called when updating image height, the argument `height` might be `0` |
| `animated` | bool | ✖ | `false` | Use `Animated.Image` instead of `Image` |
Other [image props](https://reactnative.dev/docs/image#props) except `resizeMode` are accepted.
## Change Log
[Change log](./CHANGELOG.md)
## Contributing
[Contributing](./CONTRIBUTING.md)
## Licence
[MIT](./LICENSE)
## Contributors
### Code Contributors
This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
### Financial Contributors
Become a financial contributor and help us sustain our community. [[Contribute](https://opencollective.com/react-native-auto-height-image/contribute)]
#### Individuals
#### Organizations
Support this project with your organization. Your logo will show up here with a link to your website. [[Contribute](https://opencollective.com/react-native-auto-height-image/contribute)]
## Related Projects
- [react-native-scalable-image](https://github.com/ihor/react-native-scalable-image)
- [react-native-fit-image](https://github.com/huiseoul/react-native-fit-image)
- [react-native-responsive-image-view](https://github.com/wKovacs64/react-native-responsive-image-view)
- [react-native-auto-image](https://github.com/egorshulga/react-native-auto-image)
================================================
FILE: cache.js
================================================
/**
* @since 2017-04-24 20:50:41
* @author vivaxy
*/
import { Image } from 'react-native';
// undocumented but part of react-native; see
// https://github.com/facebook/react-native/issues/5603#issuecomment-297959695
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
/**
* store with
* key: image
* value: {
* width: 100,
* height: 100,
* }
*/
const cache = new Map();
const getImageSizeFromCache = (image) => {
if (typeof image === 'number') {
return cache.get(image);
} else {
return cache.get(image.uri);
}
};
const loadImageSize = (image) => {
return new Promise((resolve, reject) => {
//number indicates import X or require(X) was used (i.e. local file)
if (typeof image === 'number') {
const { width, height } = resolveAssetSource(image);
resolve({ width, height });
} else {
Image.getSize(
image.uri,
(width, height) => {
// success
resolve({ width, height });
},
reject
);
}
});
};
export const getImageSizeFitWidthFromCache = (image, toWidth, maxHeight) => {
const size = getImageSizeFromCache(image);
if (size) {
const { width, height } = size;
if (!width || !height) return { width: 0, height: 0 };
const scaledHeight = (toWidth * height) / width;
return {
width: toWidth,
height: scaledHeight > maxHeight ? maxHeight : scaledHeight
};
}
return {};
};
const getImageSizeMaybeFromCache = async (image) => {
let size = getImageSizeFromCache(image);
if (!size) {
size = await loadImageSize(image);
if (typeof image === 'number') {
cache.set(image, size);
} else {
cache.set(image.uri, size);
}
}
return size;
};
export const getImageSizeFitWidth = async (image, toWidth, maxHeight) => {
const { width, height } = await getImageSizeMaybeFromCache(image);
if (!width || !height) return { width: 0, height: 0 };
const scaledHeight = (toWidth * height) / width;
return {
width: toWidth,
height: scaledHeight > maxHeight ? maxHeight : scaledHeight
};
};
================================================
FILE: helpers.js
================================================
export const NOOP = () => {};
export const DEFAULT_HEIGHT = 0;
================================================
FILE: index.d.ts
================================================
import * as React from 'react';
import { ImageProps } from 'react-native';
interface TSource {
uri: string;
}
export interface AutoHeightImageProps extends ImageProps {
source: number | TSource;
width: number;
maxHeight?: number;
fallbackSource?: number | TSource;
onHeightChange?: (height: number) => void;
animated?: boolean;
}
declare class AutoHeightImage extends React.Component<
AutoHeightImageProps,
any
> {}
export default AutoHeightImage;
================================================
FILE: index.js
================================================
import ErrorableImage from './ErrorableImage';
export default ErrorableImage;
================================================
FILE: package.json
================================================
{
"name": "react-native-auto-height-image",
"version": "3.2.4",
"description": "react-native auto height image",
"main": "./index.js",
"typings": "./index.d.ts",
"scripts": {
"release": "standard-version && git push --follow-tags && npm publish",
"release:beta": "standard-version --prerelease beta && git push --follow-tags && npm publish",
"postinstall": "husky install",
"prepublishOnly": "pinst --disable",
"postpublish": "pinst --enable"
},
"repository": {
"type": "git",
"url": "git@github.com:vivaxy/react-native-auto-height-image.git"
},
"keywords": [
"react-native",
"image",
"auto-height",
"react",
"images"
],
"author": "vivaxy",
"license": "MIT",
"dependencies": {
"prop-types": "^15.7.2"
},
"devDependencies": {
"@commitlint/cli": "^12.0.0",
"@commitlint/config-conventional": "^12.0.0",
"husky": "6",
"lint-staged": "^11.0.0",
"pinst": "^2.1.4",
"prettier": "^2.0.0",
"react": "^17.0.0",
"react-native": "^0.64.0",
"standard-version": "^9.0.0"
},
"peerDependencies": {
"react": "^17.0.0",
"react-native": "^0.64.0"
},
"lint-staged": {
"**/**.{js,json,md,ts}": [
"prettier --write",
"git add"
]
},
"prettier": {
"singleQuote": true,
"trailingComma": "none",
"arrowParens": "always"
},
"commitlint": {
"extends": [
"@commitlint/config-conventional"
],
"rules": {
"header-max-length": [
0,
"never"
]
}
}
}
================================================
FILE: renovate.json
================================================
{
"extends": [
"config:base",
":preserveSemverRanges"
]
}