'conditional statement in react native image source

"react": "16.8.3",
"react-native": "0.59.5",

i want to use local images and uri whenever i want, i wrote a component to do this for me according to props sent to it. but it seems conditional statement doesn't work in react native image, or require doesn't work with dynamic strings.

const CustomImage = ({ img, url, size, rounded, style, onClick }) => {
    alert('imageeeeeeeeeeee', typeof (img));
    let REQURE_STATEMENT= null;
    if (img !== null) {
        REQURE_STATEMENT= require('./../src/assets/images/close.png');
    }
    return (
        <TouchableOpacity activeOpacity={0.85} onPress={()=> onClick() }>
            <Image
                source={url === null ? REQURE_STATEMENT: { uri: url }}
                style={{ width, height, borderRadius: rounded, backgroundColor: 'red', ...(style) }}
                onPress={() => console.log('clickkkkkkkkkkkkkkkkkkkkkkkkkk')}
            />
        </TouchableOpacity>

    );
};

i even tried

let path= `./../path/${imageName}`
 <Image source={url === null ? require(path): { uri: url }}/>

but it fails with this error:

why not support error: bundling failed: Error: error: bundling failed: Error: components\common\CustomImage.js:Invalid call at line 42: require(image)
    at C:\Users\ui4\Desktop\react-git\mbz-mobile-app\node_modules\metro\src\JSTransformer\worker.js:317:19
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (C:\Users\ui4\Desktop\react-git\mbz-mobile-app\node_modules\metro\src\JSTransformer\worker.js:75:24)
    at _next (C:\Users\ui4\Desktop\react-git\mbz-mobile-app\node_modules\metro\src\JSTransformer\worker.js:95:9)


Solution 1:[1]

you can do it outside the Image component like this:

const CustomImage = ({ img, url, size, rounded, style, onClick }) => {
  alert('imageeeeeeeeeeee', typeof (img));
  let REQURE_STATEMENT= null;
  if (img !== null) {
    REQURE_STATEMENT= require('./../src/assets/images/close.png');
  }
  return (
    <TouchableOpacity activeOpacity={0.85} onPress={()=> onClick() }>
      {url === null ? (
        <Image
          source={REQURE_STATEMENT}
          style={{ width, height, borderRadius: rounded, backgroundColor: 'red', ...(style) }}
          onPress={() => console.log('clickkkkkkkkkkkkkkkkkkkkkkkkkk')}
        />
      ) : (
        <Image
          source={{ uri: url }}
          style={{ width, height, borderRadius: rounded, backgroundColor: 'red', ...(style) }}
          onPress={() => console.log('clickkkkkkkkkkkkkkkkkkkkkkkkkk')}
        />
      )}
    </TouchableOpacity>
  );
};

Solution 2:[2]

In case someone is still struggling...

<Image source={dynamicUrl ? {uri: dynamicUrl} : require(defaulPathtString) />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kenmistry
Solution 2 Afzal Ali