reactjs how to import an image from a variable path

You can try with:

Using import for browser and nodejs

const picture = (await import(`../path/to/file/${this.props.picPath}`)); // this is async

Using require for browser and nodejs

const picture = require(`../path/to/file/${this.props.picPath}`); // this is sync

Using readFileSync from fs only for nodejs

const fs = require('fs')
// or: import fs from 'fs'

const file = fs.readFileSync(`../path/to/file/${this.props.picPath}`).toString()

Using readFile from fs only for nodejs

const fs = require('fs')
// or: import fs from 'fs'
const file = (await fs.readFile(`../path/to/file/${this.props.picPath}`)).toString()

Tip #1:

When you using require, it only can handle json and js files, but when you using import, it can handle svg, and other stuff. But you can apply some trick like:

// in tsconfig.json
"include": [
    "./declarations.d.ts",
],
// in declaration.d.ts
declare module '*.png';

Tip #2:

When you wanna import images like png, you should be define how it work with this:

declare module "*.png" {
  const value: any;
  export default value;
}

Tip #3 In javascript you can use Template Literals using `` and ${}.

const name = "John"
console.log(`Hello ${name}`);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top