Code Monkey home page Code Monkey logo

react-native-auto-height-image's Introduction

react-native-auto-height-image

Initialized by vivaxy/gt-npm-package

NPM Version NPM Downloads MIT License Conventional Commits Financial Contributors on Open Collective Maintainers Wanted DOI

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:

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 (
      <View>

        <AutoHeightImage
          width={100}
          source={image}
        />

        <AutoHeightImage
          width={100}
          source={{uri: 'http://placehold.it/350x150'}}
        />

      </View>
    );
  }
}

You can even specify fallback images for when the source fails to load:

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 (
      <AutoHeightImage
        width={100}
        source={{uri: 'https://vivaxy.github.io/404'}}
        fallbackSource={image}
      />
    );
  }
}

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 except resizeMode are accepted.

Change Log

Change log

Contributing

Contributing

Licence

MIT

Contributors

Code Contributors

This project exists thanks to all the people who contribute. [Contribute].

Financial Contributors

Become a financial contributor and help us sustain our community. [Contribute]

Individuals

Organizations

Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]

Related Projects

react-native-auto-height-image's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-auto-height-image's Issues

passing headers does not work

Hello ,
I tried to pass Authorization header in headers object but it doesn't work, but it works with component ,maybe it's a bug?

React-Native 0.56.0: Trailing comma in element is causing bundle error

Issue is quite similar to mjsolidarios/react-native-search-filter#16.

Bundling with React-Native 0.56.0 leads to this error:

error: bundling failed: SyntaxError: ... node_modules/react-native-auto-height-image/autoHeightImageWithErrorFallback.js: A trailing comma is not permitted after the rest element (19:24)

    const {
        source,
        fallbackSource,
        onError,
        ...restProps,
    } = this.props;

Oh, I just saw its fixed on master. Would be cool if you could push an 1.0.1 with this fix.

Image caching?

Is your feature request related to a problem? Please describe.
We're using the plugin in a Modal which loads the images from a URI based on the image clicked on a slider. However, every time I click on the same image, it loads the image again from the source.

Describe the solution you'd like
Cache the image so the next time the resource image is accessed, it will be from cache. OR at least set something like 'only-if-cached' from React Native Image.

👀YOU DON'T NEED THIS LIB!!!

Replace this lib,
You just need to do:

import FastImage from "react-native-fast-image"

const AutoHeightImage = React.memo(function AutoHeightImage({ width, ...props }: ImageProps) {
  const [state, setstate] = React.useState(0)
  return (
    <FastImage 
      {...props}
      style={{ width: width, height: state }}
      onLoad={(evt) => {
        setstate((evt.nativeEvent.height / evt.nativeEvent.width) * width)
      }}
    />
  )
})

Simple to use:

<AutoHeightImage width={300} />

Web support

Hi,

I think it would be cool if this lib had web support.
I tested and it didn't work great for me, it seems height stays at 0 and there's an uncaught promise error:

image

If this is something you want to support, I can try to make it happen

[v3.1.0] Android crash: TypeError: _animatableImage.default.prefetch is not a function

Describe the bug
After update from v3.0.0 to v3.1.0 this library crash when running on Android.

To Reproduce
Steps to reproduce the behavior:

  1. Codes:
<AutoHeightImage
  width={Constants.deviceWidth}
  source={{ uri: image_url }}
  resizeMethod="resize"
  fallbackSource={Images.Default}
/>
  1. react-native run-android
  2. See error
    TypeError: _animatableImage.default.prefetch is not a function

Screenshots
Screenshot_1585932766

Support local images

It would be nice if this component would support local images and not just remote image urls.

componentWillReceiveProps is deprecated (in dependency)

Describe the bug
Right now, there is this warning on every mounting:

Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-async-component-lifecycle-hooks for details.

This is happening b/c react-native-image-polyfill is using it. I looked at its repo, looks like it is abandoned for a while. I suggest either getting rid of this dependency or incorporating its code into the codebase and fixing ourselves. If that is something you are ok with, I can work on a PR.

How to handle unresolved promise rejection

Hi Vivaxy,
First of all, thanks for your simple yet great component!
I've encountered an issue when trying lo load remote images that are not actually images (Because they've been removed for example). When this happens I'm getting the following:

YellowBox.js:71 Possible Unhandled Promise Rejection (id: 64):
Error: Unexpected HTTP code Response{protocol=h2, code=403, message=, url=some URL that doesn't return an Image}
Error: Unexpected HTTP code Response{protocol=h2, code=403, message=, url=some URL that doesn't return an Image}
at createErrorFromErrorData (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4551:15)
at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4509:25
at MessageQueue.__invokeCallback (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4830:16)
at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4676:16
at MessageQueue.__guard (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4765:9)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4675:12)
at t (file:///Applications/React%20Native%20Debugger.app/Contents/Resources/app.asar/js/RNDebuggerWorker.js:1:18504)

That's fine because I have an onError handler on the component that creates the AutoHeightImage component and I'm taking appropriate actions.

However, I realized that the Warning was being generated by the following function in your code:

const getImageSizeMaybeFromCache = async(imageURL) => {
    let size = getImageSizeFromCache(imageURL);
    if (!size) {
        size = await loadImageSize(imageURL);
        cache.set(imageURL, size);
    }
    return size;
};

I kind of fixed this with the following change (quick and dirty solution):

const getImageSizeMaybeFromCache = async(imageURL) => {
    let size = getImageSizeFromCache(imageURL);
    if (!size) {
        try {
            size = await loadImageSize(imageURL);    
        } catch (error) {
            size = 0 //This should probably be handled better
        }
        finally {
            cache.set(imageURL, size);            
        }
    }
    return size;
};

At least with this I managed to remove the Yellow Warning.

I hope it helps you. And let me know if you have any suggestions.

Thanks again!!

Height doesn't change. Same behaviour as Image

It seems that height is not changed, testing on iOS simulator, and still the same extra height is calculated

image

The blue background is backgroundColor: 'blue' to the

Using as follows:

<AutoHeightImage
                resizeMethod="resize"
                resizeMode="contain"
                style={styles.postContentImage}
                source={{ uri: itemImageUrl }}>
</AutoHeightImage>

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Image doesn't respond to orientation changes

I am sizing the image to the window width and the image height doesn't seem to update when a new width is passed to the component.

Looking at the code it looks like the image is only updated if the height is 0 (DEFAULT_HEIGHT). Shouldn't updateImageHeight also check to see if the width prop has changed?

Support Animated.Image

It would be awesome if this Library could support the Animated API of React-Native.

Solution:
Add an animated property which renders a Animated.Image instead of a Image if it is set to true.

[Unhandled promise rejection: Error: Failed to getSize of ...]

Describe the bug

It seems the error handling is not working. When using a failing URI, I get thrown a warning:

[Unhandled promise rejection: Error: Failed to getSize of ...] where ... is the URI

The onError prop never fires either.

Expected behavior
The onError callback should fire and there should not be an unhandled promise.

Additional context/Dependencies
I'm using Expo, here is my diagnostics:

  Expo CLI 3.28.0 environment info:
    System:
      OS: macOS 10.15.7
      Shell: 5.7.1 - /bin/zsh
    Binaries:
      Node: 12.18.4 - /usr/local/bin/node
      Yarn: 1.22.5 - /usr/local/bin/yarn
      npm: 6.14.6 - /usr/local/bin/npm
    Managers:
      CocoaPods: 1.9.3 - /usr/local/bin/pod
    SDKs:
      iOS SDK:
        Platforms: iOS 14.0, DriverKit 19.0, macOS 10.15, tvOS 14.0, watchOS 7.0
      Android SDK:
        API Levels: 28
        Build Tools: 28.0.3
    IDEs:
      Android Studio: 4.1 AI-201.8743.12.41.6858069
      Xcode: 12.0.1/12A7300 - /usr/bin/xcodebuild
    npmPackages:
      expo: ~39.0.2 => 39.0.3 
      react: 16.13.1 => 16.13.1 
      react-dom: 16.13.1 => 16.13.1 
      react-native: https://github.com/expo/react-native/archive/sdk-39.0.3.tar.gz => 0.63.2 
      react-native-web: ~0.13.12 => 0.13.15 
    npmGlobalPackages:
      expo-cli: 3.27.13
    Expo Workflow: managed

GIF is not supported for iOS

Describe the bug
I'm using this library for getting image height for remote images. I'm getting all images on Android but gif is not showing on iOS (only).

To Reproduce
You can easily do this by giving a remote GIF URL

Expected behavior
GIF should be shown on iOS side too

Screenshots
Screenshot 2021-11-09 at 16 09 37
Screenshot 2021-11-09 at 16 09 16

Dependencies versions (please complete the following information):

  • react: 16.13.1
  • react-native: ~0.63.4

Maintainers/Help needed ! 🙏

I am looking for people/companies to help maintain this component.

Currently the only maintainer is @vivaxy and I don't have enough time and resources to keep up with all the issues and questions that we have opened. I don't even use it anymore since 4 years ago.

Please get in touch if you think you can and want to maintain this project.

Thank you!

Lazy loading?

Is there any possibility or solution to lazy load an auto height image component? In a large list with several images it is downloading all images at once I believe.

After RN & Expo update web version fails

Describe the bug
After updating Expo to v44 I started to get following bugs on Web version that stops app from starting. Apps works without any issues in Android & iOs. I was not able to monkey-patch it, though I'm not saying it's not possible.

Web Bundling complete 11408ms
./node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:68:10
"export 'default' (imported as 'EmitterSubscription') was not found in './_EmitterSubscription'
  66 |     return (this._subscriber.addSubscription(
  67 |       eventType,
> 68 |       new EmitterSubscription(this, this._subscriber, listener, context),
     |          ^
  69 |     ): any);
  70 |   }
  71 |
./node_modules/react-native/Libraries/Performance/Systrace.js:216:3
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
  214 |   // with numeric IDs
  215 |   // TODO(davidaurelio) Scan polyfills for dependencies, too (t9759686)
> 216 |   (require: $FlowFixMe).Systrace = Systrace;
      |   ^
  217 | }
  218 |
  219 | module.exports = Systrace;

And this in web console.log:

Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
    at Module.<anonymous> (_EmitterSubscription.js:60:1)
    at Module../node_modules/react-native/Libraries/vendor/emitter/_EmitterSubscription.js (_EmitterSubscription.js:60:1)
    at __webpack_require__ (bootstrap:789:1)
    at fn (bootstrap:100:1)
    at Module.<anonymous> (_EventEmitter.js:12:1)
    at Module../node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js (_EventEmitter.js:173:1)
    at __webpack_require__ (bootstrap:789:1)
    at fn (bootstrap:100:1)
    at Module../node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js (EventEmitter.js:14:1)
    at __webpack_require__ (bootstrap:789:1)
    at fn (bootstrap:100:1)
    at Module.<anonymous> (Dimensions.js:11:1)
    at Module../node_modules/react-native/Libraries/Utilities/Dimensions.js (Dimensions.js:142:1)
    at __webpack_require__ (bootstrap:789:1)
...

To Reproduce
Steps to reproduce the behavior:

  1. Codes:
import AutoHeightImage from "react-native-auto-height-image";
...
            <AutoHeightImage
              resizeMode="contain"
              width={200}
              source={{ uri: uri }}
            />
...
  1. Start Expo app and then web version
  2. Wait for error in console & web console

Expected behavior
App is expected to run

Dependencies versions (please complete the following information):

PLEASE RELEASE!

Please release v3.2.5!

Current version wants react native 0.63.0 as a peer dependency, which raises a dependency resolution error.

It seems that the latest committed version of this repository specifies react-native 0.64.0.

Thanks!

3.00 - Warning: Can't perform a React state update on an unmounted component.

I'm a bit light on details, but I believe this relates to:

  • The addition of hooks support in this library, in 3.00
  • An error occurring / being handled after the component unmounts

ExceptionsManager.js:126 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
in AutoHeightImage (at autoHeightImageWithErrorFallback.js:13)
in ErrorableImage (at my_screen.js:12345)
in RCTView (at createAnimatedComponent.js:151)
in AnimatedComponent (at TouchableOpacity.js:308)
in TouchableOpacity (at listing.js:910)
in RCTView (at listing.js:908)
in RCTView (at listing.js:901)

Dependencies versions (please complete the following information):

  • react: 16.12.0
  • react-native: 0.61.5

Additional context

Works in 2.00, broken in 3.00

After RN & Expo update web version fails

Describe the bug
After updating Expo to v44 I started to get following bugs on Web version that stops app from starting. Apps works without any issues in Android & iOs. I was not able to monkey-patch it, though I'm not saying it's not possible.

Web Bundling complete 11408ms
./node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:68:10
"export 'default' (imported as 'EmitterSubscription') was not found in './_EmitterSubscription'
  66 |     return (this._subscriber.addSubscription(
  67 |       eventType,
> 68 |       new EmitterSubscription(this, this._subscriber, listener, context),
     |          ^
  69 |     ): any);
  70 |   }
  71 |
./node_modules/react-native/Libraries/Performance/Systrace.js:216:3
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted
  214 |   // with numeric IDs
  215 |   // TODO(davidaurelio) Scan polyfills for dependencies, too (t9759686)
> 216 |   (require: $FlowFixMe).Systrace = Systrace;
      |   ^
  217 | }
  218 |
  219 | module.exports = Systrace;

And this in web console.log:

Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'
    at Module.<anonymous> (_EmitterSubscription.js:60:1)
    at Module../node_modules/react-native/Libraries/vendor/emitter/_EmitterSubscription.js (_EmitterSubscription.js:60:1)
    at __webpack_require__ (bootstrap:789:1)
    at fn (bootstrap:100:1)
    at Module.<anonymous> (_EventEmitter.js:12:1)
    at Module../node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js (_EventEmitter.js:173:1)
    at __webpack_require__ (bootstrap:789:1)
    at fn (bootstrap:100:1)
    at Module../node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js (EventEmitter.js:14:1)
    at __webpack_require__ (bootstrap:789:1)
    at fn (bootstrap:100:1)
    at Module.<anonymous> (Dimensions.js:11:1)
    at Module../node_modules/react-native/Libraries/Utilities/Dimensions.js (Dimensions.js:142:1)
    at __webpack_require__ (bootstrap:789:1)
...

To Reproduce
Steps to reproduce the behavior:

  1. Codes:
import AutoHeightImage from "react-native-auto-height-image";
...
            <AutoHeightImage
              resizeMode="contain"
              width={200}
              source={{ uri: uri }}
            />
...
  1. Start Expo app and then web version
  2. Wait for error in console & web console

Expected behavior
App is expected to run

Dependencies versions (please complete the following information):

Extract the calculated Height

I'll be happy if you can implement a way to use the calculated height value. It will save us a lot of time to make modals for viewing photos.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.