How to specify the more than one uri for the image in react native?

Viewed 5333

This documentation says that:

This prop can also contain several remote URLs, specified together with their width and height and potentially with scale/other URI arguments.

Can anyone tell how to specify more than one URI's for image component in react-native? There is no such example for this definition. And also how to pass the height and width arguments along with the URI as this documentation states.

1 Answers

You can find the answer in the react-native source code, specifically /node_modules/react-native/Libraries/Image and the files ImageSourcePropType and ImageProps.

According to ImageSourcePropType, when passing a URI object, it should be in this shape (meaning it can have any of the defined properties as long as the type matches what is expected):

const ImageURISourcePropType = PropTypes.shape({
  uri: PropTypes.string,
  bundle: PropTypes.string,
  method: PropTypes.string,
  headers: PropTypes.objectOf(PropTypes.string),
  body: PropTypes.string,
  cache: PropTypes.oneOf([
    'default',
    'reload',
    'force-cache',
    'only-if-cached',
  ]),
  width: PropTypes.number,
  height: PropTypes.number,
  scale: PropTypes.number,
});

And according to ImageProps, source permits an object of shape ImageSourcePropType, an array of those objects, or a number (for local assets, the statement require('imgs/image1.png') returns a number identifying that asset). Here is the code:

const ImageSourcePropType = PropTypes.oneOfType([
  ImageURISourcePropType,
  // Opaque type returned by require('./image.jpg')
  PropTypes.number,
  // Multiple sources
  PropTypes.arrayOf(ImageURISourcePropType),
]);

So the source prop will accept a single object that matches ImageURISourcePropType or an array of objects that match.

So to pass multiple remote images and specify the widths it would be something like

<Image
  source={[
    {
      uri: 'https://image.location.com',
      width: 500,
      height: 500
    },
    {
      uri: 'https://image2.location.com',
      width: 600,
      height: 600
    },
    {
      uri: 'https://image3.location.com',
      width: 700,
      height: 700
    },
  ]}
/>
Related