Home > front end >  Pass Custom Relative Image source to Image Tag React Native
Pass Custom Relative Image source to Image Tag React Native

Time:09-22

I am trying to create a custom component in React Native which contains an Image tag with a custom source to be passed to it. The problem now is, I am getting an error that says Invalid call at line 17: require(imageSrc).

This is my GoalButton component code below:

const GoalButton = ({
  buttonStyle,
  onPress,
  text,
  imageSrc,
  imageStyle,
  textStyle,
}) => {
  return (
    <TouchableOpacity onPress={onPress}>
      <View style={buttonStyle}>
        <Image style={imageStyle} source={require(imageSrc)} />
        // Above line is Line 17
        <Text style={textStyle}>{text}</Text>
      </View>
    </TouchableOpacity>
  );
};

GoalButton.defaultProps = {
  buttonStyle: styles.buttonStyle,
  onPress: () => null,
  imageStyle: styles.imageStyle,
  textStyle: styles.textStyle,
};

export default GoalButton;

And I call it from outside like this:

<GoalButton text={'Meal Plan'} imageSrc={'../assets/images/plate.png'} />;

My question is, is there a way I can pass a relative image URL to the component and access it without any error like I was using it directly on the Image component.

CodePudding user response:

it is not possible, you can looked this,

https://stackoverflow.com/questions/30854232/react-native-image-require-module-using-dynamic-names#:~:text=The only allowed way to refer to an image in the bundle is to literally write require('image!name-of-the-asset') in the source.

  • Related