Skip to content

Commit

Permalink
feat: support onLoad, onError and fallbackSource
Browse files Browse the repository at this point in the history
  • Loading branch information
sepperousseau committed Oct 31, 2023
1 parent 7e56393 commit c0c3420
Showing 1 changed file with 19 additions and 13 deletions.
32 changes: 19 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const NativeBlastedImage = NativeModules.BlastedImage

const BlastedImageView = requireNativeComponent('BlastedImageView');

const BlastedImage = ({ source, width, height, style, resizeMode, isBackground, children }) => {
const BlastedImage = ({ source, width, onLoad, onError, fallbackSource, height, style, resizeMode, isBackground, children }) => {
const [error, setError] = useState(false);

if (!source || (!source.uri && typeof source !== 'number')) {
Expand All @@ -48,9 +48,11 @@ const BlastedImage = ({ source, width, height, style, resizeMode, isBackground,
const fetchImage = async () => {
try {
await loadImage(source.uri, source.headers);
onLoad?.();
} catch (err) {
setError(true);
console.error(err);
onError?.(err);
}
};

Expand Down Expand Up @@ -84,7 +86,7 @@ const BlastedImage = ({ source, width, height, style, resizeMode, isBackground,
console.log("For maximum performance, BlastedImage does not support width defined as a percentage");
return;
}

if (typeof height === 'string' && height.includes('%')) {
console.log("For maximum performance, BlastedImage does not support height defined as a percentage");
return;
Expand All @@ -109,31 +111,35 @@ const BlastedImage = ({ source, width, height, style, resizeMode, isBackground,
alignItems:'center',
width: adjustedWidth,
height: adjustedHeight,
};
};

return (
<View style={!isBackground ? viewStyle : null}>
{isBackground ? (
<View style={viewStyle}>
{renderImageContent(error, source, adjustedHeight, adjustedWidth, resizeMode)}
{renderImageContent(error, source, fallbackSource, adjustedHeight, adjustedWidth, resizeMode)}
</View>
) : (
renderImageContent(error, source, adjustedHeight, adjustedWidth, resizeMode)
renderImageContent(error, source, fallbackSource, adjustedHeight, adjustedWidth, resizeMode)
)}
{isBackground && <View style={childrenStyle}>{children}</View>}
</View>
);
};

function renderImageContent(error, source, adjustedHeight, adjustedWidth, resizeMode) {
function renderImageContent(error, source, fallbackSource, adjustedHeight, adjustedWidth, resizeMode) {
if (error) {
return (
<Image
source={require('./assets/image-error.png')}
style={{ width: adjustedHeight, height: adjustedHeight }}
resizeMode={resizeMode}
/>
);
if (fallbackSource) {
return (
<Image
source={fallbackSource}
style={{ width: adjustedHeight, height: adjustedHeight }}
resizeMode={resizeMode}
/>
);
} else {
return null;
}
} else if (typeof source === 'number') {
return (
<Image
Expand Down

0 comments on commit c0c3420

Please sign in to comment.