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.
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:
require
ing once be more performant like I suspect? Or am I just imagining it. Thanks in advance!
If I want to use an image multiple times in my application, then I will do something like this.
export const Likes = require('./assets/images/like.png')
export const DefaultAvatar = require('./assets/images/default-avatar.png')
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 :)