Git Product home page Git Product logo

react-preload's Introduction

React Preload

npm version

A React component to preload images. It renders a passed component during the loader phase, and renders its children once the images have been successfully fetched.

Installation

npm

npm install react-preload --save

Usage

var Preload = require('react-preload').Preload;
var loadingIndicator = (<div>Loading...</div>);
var images = [];

<Preload
    loadingIndicator={loadingIndicator}
    images={images}
    autoResolveDelay={3000}
    onError={this._handleImageLoadError}
    onSuccess={this._handleImageLoadSuccess}
    resolveOnError={true}
    mountChildren={true}
>
    {/* content to be rendered once loading is complete */}
</Preload>

Prop types

propTypes: {
    // Rendered on success
    children: PropTypes.element.isRequired,

    // Rendered during load
    loadingIndicator: PropTypes.node.isRequired, // Default: null

    // Array of image urls to be preloaded
    images: PropTypes.array, // Default: []

    // If set, the preloader will automatically show
    // the children content after this amount of time
    autoResolveDelay: PropTypes.number,

    // Error callback. Is passed the error
    onError: PropTypes.func,

    // Success callback
    onSuccess: PropTypes.func,

    // Whether or not we should still show the content
    // even if there is a preloading error
    resolveOnError: PropTypes.bool, // Default: true

    // Whether or not we should mount the child content after
    // images have finished loading (or after autoResolveDelay)
    mountChildren: PropTypes.bool, // Default: true
}

Additional Details

This module also exposes ImageCache and ImageHelper which can be used to preload images directly, and can be accessed via require('react-preload').ImageCache and require('react-preload').ImageHelper respectively.

License

MIT

react-preload's People

Contributors

anhulife avatar claus avatar mesoptier avatar npmcdn-to-unpkg-bot avatar ohall avatar pgraci avatar sambernard avatar

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

react-preload's Issues

Usage of the cache

The concept of main cache is great, but, there is no documentation about it.
Would be great to have a section of the read me that talk about it

Failed to minify ImageHelper.js

I'm using the Preload package in my app , I use webpack to bundle and minify everything using the HtmlWebpackPlugin with minifyjs set to true. When I build the project with this package installed I get the following error:

Failed to minify the code from this file:

    ./node_modules/react-preload/lib/ImageHelper.js:3

Any hints as to how I could solve this?

It appears that it isn't transpiled to ES5. According to the following link:

https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#npm-run-build-fails-to-minify

I'll try create a transpiled version.

cache overflow and ready prop features

Hi, the component looks nice, unfortunately I cannot use it as is for my use case, which is:

SPA that shows pages of images, preloading the next page until the user forces it to show.

This can be supported by adding two features:

  1. Pass a ready prop that would override internal state and show the children, which would allow an external event like user interaction to affect things regardless of preload status.
  2. Specify max cache size that would ensure older images get dropped from the cache.

I can work around the "ready prop" by doing something like:

render() {
  const {ready, children, ...other} = this.props
  return (
    {ready ? <Preload {...other}>{children}</Preload> : {children}}
  )
}

But seems that encapsulating this may be cleaner.

Cannot import preload

This is the error that I get when I try to use preload in my project.

(function (exports, require, module, __filename, __dirname) { import _Preload from './Preload';

Preload images with hashes

I want to preload multiple images in folder using require.context as follows:

let images = require.context("../assets/images", false, /\.(png|jpe?g|svg)$/).keys(); images = images.map(image => image.replace("./", "../assets/images/"));

It loads all images as expected, but without hashes. Create-react-app insert hashes by default when importing images.

How can I add hashes into my array of images?

Preload is undefined

Hi, I was trying to use this in a project, but I use es6 so the var Preload = require("react-preload");
becomes import Preload from "react-preload"

but Preload is undefined and I can not render the component, any ideas ?

Uncaught TypeError: Super expression must either be null or a function, not undefined

Hey first up, just want to say this a cool repo. Anyway I am having some issues with the setup and just wondering if there is something obvious I am missing but I am getting this exception

Uncaught TypeError: Super expression must either be null or a function, not undefined

My package.json file looks like this

"dependencies": {
    "react": "^0.12.2",
    "react-addons": "^0.9.0",
    "react-dom": "^0.14.0",
    "react-preload": "^0.2.2",
    "react-tools": "*",
    "requirejs": "*"
  },
  "devDependencies": {
    "babelify": "^6.3.0",
    "watchify": "^3.4.0"
  }

and I start my react file off like below but I get the exception straight away, I expect there is something in my setup missing but not sure yet. Fyi I am using browserify to build my js, thanks. Will

var React = require('react/addons');
var Preload = require('react-preload').Preload; 

Image flashes after component mounts

What are you doing to avoid image flashes after element mounts?
That's how I using it. After image loads, I change state to mount child component which contains same image. But image doesn't appears instantly, it looks like it's loading again, it renders progressively. (tested in chome and ff) Do you have any ideas why it may happens?

this.state = {
  imagesLoaded: false
}

...

_handleImageLoadSuccess = () => {
  this.setState({
    imagesLoaded: true
  })
}

...


<Preload
  loadingIndicator={<div/>}
  images={[imageUrl]}
  onSuccess={this._handleImageLoadSuccess}
  mountChildren={imagesLoaded} >
    <div className='my-image' style={{backgroundImage: `url(${imageUrl})`}}></div>
</Preload>

TypeError: Cannot read property 'element' of undefined

Getting:

/node_modules/react-preload/lib/Preload.js:27
children: _react.PropTypes.element.isRequired,
TypeError: Cannot read property 'element' of undefined

With Code:

const loadingIndicator = (<div>Loading...</div>)
const imagesL = [
  'img1.png',
  'img2.png',
  'img3.png'
]
<Preload
loadingIndicator={loadingIndicator}
images={imagesL}
autoResolveDelay={5000}
mountChildren={true}
resolveOnError={true}
>
  {<div>Hi</div>}
</Preload>

Make loadingIndicator prop optional

It would help if you can make loadingIndicator prop optional, I have preloader that's hardcoded into index.html file so it starts showing even before application js files are loaded. Then I hide that preloader with callback from application. So it doesn't need another loading indicator.

Package failed after upgrading React to 16.x

I upgraded React from 15.x to 16.x today. Is it possible to use this package with React 16.x ?
Im using React with Meteor and i get this Error when i try to Import the ImageHelper:

SyntaxError: import declarations may only appear at top level of a module

and a warning that i need React 15.x:

[email protected] requires a peer of react@^15.0.0 but none is installed.

Audio files preloading

It would be nice if it also can preload audio files, I have applications with many different sounds.

images not preloading on receiving new props

the component has provided a brautifully simple means of preloading a series of images on a slide show for an artists site I am developing, thank you.

The issue is that images are preloaded once only even if the component is sent a new lot of images.

For example, given a single gallery component that presents different sets of images (paintings and sculptures in this instance) when the user first clicks on paintings it pre-loads the paintings and all is well - when the user then clicks on sculptures (without returning to the home page first) no pre-loading occurs.

I believe this is because the preload component does its preloading on componentWillMount - in the containing component that passes the images I also reload data on componentWillReceiveProps to effect the switch between galleries.

Being inexperienced I am hesitent of creating a pull request before asking if this seems like a good approach for this component.

crossorigin breaks cache when using it without it

I was trying to use the ImageHelper and ImageCache to preload some background images I am using in my CSS. However, as of :
5c80e8f

it seems to break (tested in Chrome) from using the cached image in a CSS background image.

I think this crossorigin setting should be made optional.

Warning on route change

It appears switching to a new route while images are still preloading will cause an error. This may occur because there is no componentWillUnmount to clear the event listeners?

warning.js?0260:45 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.warning @ warning.js?0260:45getInternalInstanceReadyForUpdate @ ReactUpdateQueue.js?fd2c:34ReactUpdateQueue.enqueueSetState @ ReactUpdateQueue.js?fd2c:181ReactComponent.setState @ ReactComponent.js?702a:65_handleSuccess @ Preload.js?631e:113

Feature request: bool prop to delay onSuccess/onError

It would be nice if we had a prop that delays calls to onSuccess/onError (and delays switching out content) until it is set to true (or something like that).

I have a use case where i have to do some other preloading tasks in addition to preloading images, where it would be nice if the preloader component would stay mounted even when images have already been loaded, until i tell it that it is ok to switch. Does that make sense? :)

Images failed to preload

I am always getting images failed to preload. What am I doing wrong?

let images=[
            "/assets/images/1.png",
            "/assets/images/2.png",
            "/assets/images/3.png",
            "/assets/images/4.png"
        ]
 let loadSpan= <span className="loadspan">
                              <i className="spin fa fa-refresh"/>
                          </span>
<Preload
                loadingIndicator={loadSpan}
                images={images}
                autoResolveDelay={10000}
                resolveOnError={true}
                mountChildren={true}
            >
...other select component
</Preload>

When looking at network activity they are loaded sucessfully, but library still spams console..

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.