Search code examples
reactjsreact-nativeecmascript-6commonjs

How to properly require images in ES6, React Native, CommonJS


There are a few images used everywhere in my app. Imagine a user's default avatar, like button icon, etc.

I read the React Docs but they don't go into detail about a better approach to require ing images which are used a lot.

https://facebook.github.io/react-native/docs/images

My app is structured like this

...
./assets/images/like.png
./assets/images/default-avatar.png
./components/Newsfeed.js
./components/Home.js
...

I use to require in the body of the render() function like so. But I noticed the images took quite a while to load.

render() {
  ...
  posts && posts.map(post => <Post likeUrl={require('../assets/images/like.png')}>)
  ...
}

I was experimenting so I moved the require to the top and then refactored in my Newsfeed.js and Home.js. There was indeed a noticeable improvement when these components loaded.

...

const LIKE = require('../assets/images/like.png')

export class Newsfeed extends Component {
  render() {
    ...
    posts && posts.map(post => <Post likeUrl={LIKE}>)
    ...
  }
}

I want to know if there's a way to structure the project so that I don't have to require in multiple places.

Bonus Points:

  1. Would requireing once be more performant like I suspect? Or am I just imagining it.
  2. If so, what would be a good approach to importing these images into a centralized place, making them exportable, and then importing them into another file for consumption?

Thanks in advance!


Solution

  • If I want to use an image multiple times in my application, then I will do something like this.

    1. I create a common file called 'image_container.js' and make changes like below:

    export const Likes = require('./assets/images/like.png')
    export const DefaultAvatar = require('./assets/images/default-avatar.png')

    1. I will import the images from that file to use it.

    import { Likes, DefaultAvatar } from './image_container'
    
    export class Newsfeed extends Component {
      render() {
          ...
          posts && posts.map(post => <Post likeUrl={Likes}>)
          ...
      }
    }

    By doing like this, I am requiring the images once and using it multiple times in my application.

    Hope it helps :)