0

Im new to react

I created my react project using create-react-app.

I need the same functionality as import logo from './logo.png';but for a directory.

something like import * as Images from './images/'; and Images would be an array.

I found some solutions for webpack but they obviously don't work, is this possible in my situation?

for context here is how i want to use the images. Currently, they are hardcoded into this.state.images[]

const style = {
      //overflowY: "scroll",
      height: 5000,
      width: "100%",
      backgroudImage: `url(${this.state.images[this.state.index]})`,
      backgroundPosition: "center",
      backgroundSize: "cover",
      backgroundRepeat: "no-repeat"
    }; 

Thank you in advance.

1 Answer 1

1

You can try this

Create a const to save images that you needed like

export const Images =  [
  '/assets/images/1.png', 
  '/assets/images/2.png',  
  '/assets/images/3.png'
]; 

Then in your components, import that const and render like

import { Images } from './../../utils/Image'

<React.Fragment>
{
   Images.map((item, index) =>  {
      return <div 
                key={index} 
                style={{
                  //overflowY: "scroll",
                  height: 5000,
                  width: "100%",
                  backgroundImage: `url(${item})`,
                  backgroundPosition: "center",
                  backgroundSize: "cover",
                  backgroundRepeat: "no-repeat"}}>
            </div>
   })
}
</React.Fragment>

If you set the style as className and then pass the image dynamic to the context

<React.Fragment>
{
    Images.map((item, index) =>  {
       return <div 
                  key={index} 
                  className='image-container'
                  style={{backgroundImage: `url(${item})`}}>
              </div>
  })
}
</React.Fragment>

If you are going for update the webpack, then please install the url-loader and file-loader

npm install url-loader file-loader --save-dev

then update the webpack config as

module: {
  rules: [
    {
      test: /\.(jpe?g|gif|png|svg)$/i,
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 10000
          }
        }
      ]
    }
  ],
},
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.