add variable to require in ImageBackground

336 views Asked by At

I am using ImageBackground from react-native lib. ImageBackground using source={require('asd.png')} for example.

But I am trying to add variable inside to require.

const [image,setImage] = useState('./asd.png')

.then(image => {
            setImage(image.path) // gives 'something.png'
          });

<ImageBackground source={require(image)></ImageBackground> 


But I am getting error. Invalid call at line 122: require(image)

1

There are 1 answers

13
Kartikey On
// Declare a varible here...
const img = require('./asd.png')  

// Example of a network image
const networkImage = "https://images.pexels.com/photos/799443/pexels-photo-799443.jpeg"  

const [image, setImage] = useState(img) // Use it here like this

// Static Image Usage
<ImageBackground 
    source={image} 
    style={{ flex: 1, resizeMode: 'cover', justifyContent: 'center' }}>
</ImageBackground> 

// Network Image Usage
<ImageBackground 
    source={{uri : networkImage}} 
    style={{ flex: 1, resizeMode: 'cover', justifyContent: 'center' }}>
</ImageBackground> 

This is the proper way to use ImageBackground

Check this Snack to see working example

Also, have a look at the docs for more help.

As the Docs says,

// GOOD (this is also correct)
<Image source={require('./my-icon.png')} />;

// BAD (this is wrong...)
var icon = this.props.active
  ? 'my-icon-active'
  : 'my-icon-inactive';
<Image source={require('./' + icon + '.png')} />;

// GOOD (this is correct)
var icon = this.props.active
  ? require('./my-icon-active.png')
  : require('./my-icon-inactive.png');
<Image source={icon} />;