sAleksovski / react-native-android-widget

Build Android Widgets with React Native
https://sAleksovski.github.io/react-native-android-widget/
MIT License
546 stars 22 forks source link

ImageWidget image property via variable not working #64

Closed huttonjd closed 4 months ago

huttonjd commented 4 months ago

Thank you so much for writing this so we can do widgets using react native!!

I am having an issues with ImageWidget and trying to set image via a variable. I have tried a whole bunch of combinations.

This works:

<ImageWidget style={{
        marginTop: imageTop,
        marginLeft: imageMarginLeft,
      }}
        image={require('../assets/images/accuweather/ic_accuweather_06.png')} 

        imageWidth={imageSize}
        imageHeight={imageSize}

        clickAction="OPEN_APP"
/>

None of these do

let currentDayImageSource = '../assets/images/accuweather/ic_accuweather_06.png';
...
<ImageWidget style={{
        marginTop: imageTop,
        marginLeft: imageMarginLeft,
      }}
        //image={require(`${currentDayImageSource}`)} 
        //image={`${currentDayImageSource}` as ImageWidgetSource}
        //image={`${currentDayImageSource}`}

        imageWidth={imageSize}
        imageHeight={imageSize}

        clickAction="OPEN_APP"
/>
let currentDayImageSource = require('../assets/images/accuweather/ic_accuweather_06.png');
...
<ImageWidget style={{
        marginTop: imageTop,
        marginLeft: imageMarginLeft,
      }}
        //image={`${currentDayImageSource}` as ImageWidgetSource}
        //image={`${currentDayImageSource}`}

        imageWidth={imageSize}
        imageHeight={imageSize}

        clickAction="OPEN_APP"
/>

Any help would be greatly appreciated!

sAleksovski commented 4 months ago

Dynamic file imports don't work in React Native, because they need to be known statically. See https://reactnative.dev/docs/images#static-image-resources

ImageWidget accepts several different types of images:

Your examples don't work because:

What you can do in order to have dynamic images is use an object, for example:

const images = {
  ic_01: require('../assets/images/accuweather/ic_accuweather_01.png'),
  ...
  ic_06: require('../assets/images/accuweather/ic_accuweather_06.png'),
}

and use the widget as

<ImageWidget image={images[imageKey]} ...props />

Where imageKey is "ic_06", or something that you can use from your API.

huttonjd commented 4 months ago

Thanks! You gave me what i needed to solve it!!!

I actually using a

const images = {
  ic_01: require('../assets/images/accuweather/ic_accuweather_01.png'),
  ...
  ic_06: require('../assets/images/accuweather/ic_accuweather_06.png'),
}

I just assign it to a variable above and not use it directly in the ImageWidget props like you do. I switched it to use directly in ImageWidget props and now it works!!! Yours

<ImageWidget image={images[imageKey]} ...props />