Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requiring image in react-native 0.14.2

Tags:

react-native

Doing this my code works fine

<Image
source={require('../../assets/images/music_star.png')}
style={styles.musicStar}
/>

But doing this gives me an error

let imgSource = '../../assets/images/music_star.png';
<Image
source={require(imgSource)}
style={styles.musicStar}
/>

I get an error:

Requiring unknown module "../../assets/images/music_star.png"

What am I doing wrong? How to require images stored in a variable in react-native 0.14.2?

like image 255
Aakash Sigdel Avatar asked Nov 30 '15 12:11

Aakash Sigdel


People also ask

How do I insert an image into react native?

Adding Image Let us create a new folder img inside the src folder. We will add our image (myImage. png) inside this folder. We will show images on the home screen.

How do I display a JPEG in react native?

Open App. js and add the following code: import { StatusBar } from "expo-status-bar"; import React from "react"; import { StyleSheet, Text, View, ImageBackground } from "react-native"; const staticImage = require("./src/assets/static-image. png"); export default function App() { return ( <View style={styles.

How do I fetch an image from API in react native?

To fetch image from API with React, we can use the fetch function. We call fetch with the imageUrl to make a GET request to it. Then we call res. blob to convert the response object to a blob.

How do I add a header image in react native?

To use one Image as the header image, we need to pass it as the headerTitle. We can pass one function to headerTitle props that return one Image which will be used as the header image. We can give the height and width of the title image to make it fit in the header.


1 Answers

You can read more in the docs but basically, in order for this to work, the image name in require has to be known statically:

// GOOD
<Image source={require('./my-icon.png')} />

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

// GOOD
var icon = this.props.active ? require('./my-icon-active.png') : require('./my-icon-inactive.png');

To pass an image from parent to child, you should require it in the parent:

/**
 * The entry point for the iOS app.
 */
import React, {
  AppRegistry,
  Component,
  Image,
  View,
} from 'react-native';

class Child extends Component {
  render() {
    return (
      <Image source={this.props.image} />
    )
  }
}

export default class Parent extends Component {
  render() {
    return (
      <View>
        <Child image={require('./test.png')} />
      </View>
    );
  }
}

AppRegistry.registerComponent('App', () => Parent);
like image 171
Almouro Avatar answered Sep 30 '22 19:09

Almouro