react-native-community/discussions-and-proposals

Import image like React js

raihan-ramadhan opened this issue · 2 comments

Introduction

Hi i'm new with React Native

Details

In react native to use image assets we need to use code like this
<Image source={require('./assets/icon.png')} />

but i'm prefer to use image like in react js
import MyIcon from "./assets/icon.png";
<Image source={MyIcon} />
Well actually we can use this line (atleast in my android phone), but i get ts error "Cannot find module './assets/icon.png' or its corresponding type "

Discussion points

I think it's good idea to add option to use image assets like in react js

Trusting that the image does exist, the path is correct and there is no other unrelated issue in your code, you can import the image at the top of your component like mentioned below:
const MyIcon = require("./img-path");

Also, rather than having multiple import statements for multiple images in your component, you can create a seperate .js file where you can import all the images being used in your project at once and then put export before all the import statements.
export const MyIcon = require("./img-relative-path");
export const OtherIcon = require("./img-relative-path");

Now, you can import multiple images with a single statement in your component from this .js file.

import { MyIcon, OtherIcon } from 'js-file-relative-path';

Also, rather than having multiple import statements for multiple images in your component, you can create a seperate .js file where you can import all the images being used in your project at once and then put export before all the import statements. export const MyIcon = require("./img-relative-path"); export const OtherIcon = require("./img-relative-path");

Now, you can import multiple images with a single statement in your component from this .js file.

import { MyIcon, OtherIcon } from 'js-file-relative-path';

Yes i love this multiple import images in separate .js file, so it's more maintainable, thanks for advice