0

I need to request static files from a react component's render method based on a dynamic prop, it's id in my particular case. My folder structure is similar to this, the number of images in each gallery folder is arbitrary :

-hardcode
  -id_1
   -gallery1
     -img1.jpg
     -img2.jpg
   -gallery2
     -img1.jpg
     -img2.jpg
   -data.json
  -id_2
   -gallery1
     -img1.jpg
     -img2.jpg
     -img3.jpg
   -gallery2
     -img1.jpg
   -data.json
  -id_3
    ...

Ideally, I need to get an array of image files that gallery1 and gallery2 folders contain and also get contents of data.json based on id. What would be the best way to implement that?

Umbrella
  • 1,085
  • 1
  • 14
  • 30
  • Please provide a detailed description of the issue and what the desired output should look like. Also, provide some info about how your application is setup. – Aniket Pandey Jun 21 '23 at 19:09

1 Answers1

-1

In React, you typically import static files, such as images, stylesheets, or JSON files, at the top of your component file using the import statement. This is because imports in JavaScript are static and are resolved during the compilation phase.

However, if you need to dynamically require static files within a component's render method, you can achieve it by leveraging JavaScript's dynamic capabilities. Here's an example of how you can accomplish this:

import React from 'react';

class MyComponent extends React.Component {
  render() {
    const imagePath = 'path/to/image.png'; // Path to your image file

    return (
      <div>
        <img src={require(`${imagePath}`)} alt="Dynamic Image" />
      </div>
    );
  }
}

export default MyComponent;
desertnaut
  • 57,590
  • 26
  • 140
  • 166
Feniix
  • 1