Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusable Button with image tag (React Native)

Tags:

react-native

I want to turn this section of code into a reusable component so I don't have to write the same thing out 5 times.

<TouchableOpacity onPress={console.log('pressed')}>
  <Image
    source={require('../img/button_australia.png')}
  />
</TouchableOpacity> 

The new component I made to mirror this is as follows:

import React from 'react';
import { Image, TouchableOpacity } from 'react-native';

const ImgButton = ({ onPress, img }) => {

return (
  <TouchableOpacity onPress={onPress}>
    <Image
      source={require(img)}
    />
  </TouchableOpacity>
  );
};

export { ImgButton };

After importing this component ImgButton I call it with this block of code:

  <ImgButton
     onPress={console.log("pressed")}
     img={'../img/button_australia.png'}
  />

I get the error: "Requiring unknown module '../img/button_australia.png'"

I assume I've gone wrong when passing the string down as a prop but from the examples I've looked I don't see what's wrong with what I've done. Thanks :)

like image 911
Carl Wirkus Avatar asked Dec 08 '25 14:12

Carl Wirkus


1 Answers

As discussed in this react-native issue, it's not possible to require assets or javascript modules with dynamically generated names, e.g. variables.

This is because the React Native packager uses require (and import) statements to generate the module and asset bundles at compile-time, so the value of the variable is not known.

The simplest way is to just pass the image source to the component directly:

<ImgButton
  onPress={console.log("pressed")}
  img={require('../img/button_australia.png')}
/>
like image 111
jevakallio Avatar answered Dec 11 '25 23:12

jevakallio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!