react-nativereact-navigationrouteparams

How to insert route params inside image URL in React Native / Navigation?


On my app's first screen, I have a touchable image that actually send route params to the second screen, which look like this :

<TouchableHighlight onPress={() => navigation.navigate("EcranDetails",{album_id:1,album_name:"David Bowie",album_date:1967,album_img:"david_bowie"})}>
    <Image style={styles.album} source={require('../../assets/images/albums/david_bowie.jpg')} />
</TouchableHighlight>

And on my second screen, I would like to have this (image's url string from params inside the require):

<Image style={styles.album} source={require('../../assets/images/albums/david_bowie.jpg')} />

But this code doesn't work and I can't find anything related to params in require :

<Image style={styles.album} source={require('../../assets/images/albums/',{JSON.stringify(album_img)},'.jpg')} />

Any idea why it doesn't work and how I could fix that? Thanks a lot if you can help.


Solution

  • Solution found.

    I've been told that we can't do dynamic require in React Native so I have to write the whole require into the route param to send, and it the receiver screen, in the image's source I just have to write the param name I've sent.


    Example :

    Sender screen

    <TouchableHighlight onPress={() => navigation.navigate("EcranDetails",
        {album_id:1,album_name:"David Bowie",album_date:1967,album_img:require("../../assets/images/albums/david_bowie.jpg")})}>
        <Image style={styles.album} source={require('../../assets/images/albums/david_bowie.jpg')} />
    </TouchableHighlight>
    

    Receiver screen

    const { album_id, album_name, album_date, album_img } = route.params;
    <Image style={styles.album} source={album_img} />
    

    All works fine now. HOWEVER, if for some reason it's bad practice or deprecated in any way, I'd love to know why.