Search code examples
javascriptreactjsassetsjsx

Best way to add asset path variable with React and JSX?


What is the best way to add asset path variables?

I am working on an app that has a different asset dir depending on the environment (local, staging, production).

Right now, all my image paths are hard coded in the JSX which works totally fine when developing locally. However, when on staging, the asset path is slightly different.

Here is simple example of what I'm talking about.

render() {
    return (
        <div className="home-container">
            <img className="home-container__logo" src="/images/ui/logos/imagename.png" />
        </div>
    );
}

The image src attribute points to "/images". This may be different in other environments.

Is there a "React way" of adding an asset path var or doing the equivalent of something like {% static 'images/ui/logos/imagename.png' %}?

Cheers


Solution

  • There are no built in helpers for asset paths in React, but your intuition is good: this is a good abstraction, and worth making yourself. If you're using webpack, you can set the module resolve to include a path to your root react folder, and then a simple solution might look like this:

    # app/helpers/AssetHelper.js
    export default {
      imagePath: (path) => {
        return `/images/${path}`
      }
    }
    
    # your component
    import { imagePath } from 'app/helpers/AssetHelper'
    
    render() {
      return (
        <div className="home-container">
          <img className="home-container__logo" src=${imagePath('ui/logos/imagename.png')} />
        </div>
      );
    }
    

    If you are not using Webpack or some equivalent, the path will need to be relative, and this won't be such an easy solution. If you're using webpack, check out module resolve. It will allow you to simplify your imported file paths.

    Example webpack config using module resolve:

    # webpack.config.js
    var path = require('path')
    
    module.exports = {
      entry: ...,
      output: ...,
      resolve: {
        // specify your new path relative to the webpack config file
        modules: [path.resolve(__dirname, './app'), 'node_modules']
      }
    }