UNPKG

react-native-surveys

Version:

Build your own forms, surveys and polls for your React Native apps.

105 lines (96 loc) 2.59 kB
function _extends() { _extends = Object.assign || function(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } import React, { useState, useEffect, useRef } from "react"; import { Image, TouchableOpacity, ImageBackground } from "react-native"; const ScalableImage = props => { const ImageComponent = props.background ? ImageBackground : Image; const [scalableWidth, setScalableWidth] = useState(null); const [scalableHeight, setScalableHeight] = useState(null); const [image, setImage] = useState(React.createElement(ImageComponent, null)); const mounted = useRef(false); useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []); useEffect(() => { onProps(props); }); useEffect(() => { setImage( React.createElement( ImageComponent, _extends({}, props, { style: [ props.style, { width: scalableWidth, height: scalableHeight } ] }) ) ); }, [props, scalableHeight, scalableWidth]); const onProps = localProps => { const { source } = localProps; const sourceToUse = source.uri ? source.uri : source; Image.getSize( sourceToUse, (width, height) => adjustSize(width, height, props), console.err ); }; const adjustSize = (sourceWidth, sourceHeight, localProps) => { const { width, height } = localProps; let ratio = 1; if (width && height) { ratio = Math.min(width / sourceWidth, height / sourceHeight); } else if (width) { ratio = width / sourceWidth; } else if (height) { ratio = height / sourceHeight; } if (mounted.current) { const computedWidth = sourceWidth * ratio; const computedHeight = sourceHeight * ratio; setScalableWidth(computedWidth); setScalableHeight(computedHeight); props.onSize({ width: computedWidth, height: computedHeight }); } }; if (!props.onPress) { return image; } else { return React.createElement( TouchableOpacity, { onPress: props.onPress }, image ); } }; ScalableImage.defaultProps = { background: false, onSize: () => {} }; export default ScalableImage;