0

I am learning react. I am trying to display an image and background image from an array but it's not working.

I am getting the below output.

For image

<img src="images/system_analysis.png" alt="">

For Background image

<div class="proWrapper" style="background-image: url("images/system_analysis.png");"</div>

I need to know where I have to use require for my images. I tried to use it in the array but it's not working.

 imgIcon:require+"images/system_analysis.png",

I tried below code as well but it's displaying an error

 <img src={require(props.imgIcon)} alt="" />

Note: I have more than 100 images and each image I can't import them manually

I am sharing my code here.

Main.js

import React from 'react';

const OurService = (props) => {
  return (
   <img src={props.imgIcon} alt="" />
      );
}

const OurProducts = (props) => {
  return (
  <div className="proWrapper" style={{backgroundImage: "url("+ props.bg_image + ")"}}></div> 
      );
}
export {OurService,OurProducts} 

App.js

import React from 'react';
import {OurService,OurProducts}  from './Main'
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';


const AService = () => {
  const serviceArray=[
    {
      imgIcon:"/images/system_analysis.png"
    },
    {
      imgIcon:"/images/system_analysis.png"
    },
    {
      imgIcon:"/images/system_analysis.png"
    },
    {
      imgIcon:"/images/system_analysis.png"
    }
  ]
  const serviceFor=serviceArray.map((storeServiceArray, i) => {
   return   <OurService key={i} imgIcon={serviceArray[i].imgIcon}  />
  })

  return (
    <div className="container">
      <div className="equalPadding">
        <div className="section-title text-center"><h2>Our Services</h2><p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p></div>
          <div className="row">
          {serviceFor}
          </div>
    </div>
    </div>

      );
}

const AProducts = () => {
  const productsArray=[
    {
      bg_image:"images/system_analysis.png"
    },
    {
      bg_image:"images/system_analysis.png"
    },
    {
      bg_image:"images/system_analysis.png"
    }
  ]
  const productsFor=productsArray.map((storeProductsArray, i) => {
return   <OurProducts key={i} bg_image={productsArray[i].bg_image} />
  })

  return (
    <div className="container">
      <div className="equalPadding">
        <div className="section-title text-center"><h2>Our Products</h2>
         <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p></div>
          <div className="row">
          {productsFor}
          </div>
    </div>
    </div>

      );
}

 export {AService, AProducts}

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {AService, AProducts} from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<AService />,document.getElementById('a-services'));
ReactDOM.render(<AProducts />,document.getElementById('a-products'));

serviceWorker.unregister();
ksav
  • 20,015
  • 6
  • 46
  • 66
user9437856
  • 2,360
  • 2
  • 33
  • 92

2 Answers2

1

For dynamic path, you have to use template strings.

So instead of doing this, <img src={require(props.imgIcon)} alt="" />.

Do this

<img src={require(`${props.imgIcon}`)} alt="" />

EDIT

Also, make sure to provide the correct path. Try adding a dot . to your image path. Like this /images/system_analysis.png

Working copy of the code is here:

https://codesandbox.io/s/image-bg-image-wookp?file=/src/Main.js

gdh
  • 13,114
  • 2
  • 16
  • 28
  • I tried this but I am getting error Attempted import error: './App' does not contain a default export (imported as 'App'). – user9437856 Apr 13 '20 at 05:11
  • please check if you are doing any `default import` in your code somewhere for the app component.. – gdh Apr 13 '20 at 05:22
  • I am new in react. I am using only code which I added in the question. I am not using any default import I guess. – user9437856 Apr 13 '20 at 05:26
  • I took your code adn tried using template string .. it is working ... one change for you to make is to add a dot `.` to your image path ... instead of `/images/....` , do `./images/system_analysis.png` .. indicate ... i will update my answer with a working example .. leave a comment if any further issues – gdh Apr 13 '20 at 06:07
  • Give me some time to check your answer – user9437856 Apr 13 '20 at 06:13
  • I checked. I am still getting Attempted import error: './App' does not contain a default export (imported as 'App'). Check this image https://prnt.sc/ry7cnm – user9437856 Apr 13 '20 at 06:24
  • Is this correct code import {AService, AProducts} from './App'; i am getting issue in this – user9437856 Apr 13 '20 at 06:30
  • yes it is correct.. because you are doing named export in App.js (i.e. `export { AService, AProducts };` – gdh Apr 13 '20 at 06:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/211526/discussion-between-gdh-and-user9437856). – gdh Apr 13 '20 at 06:33
  • Yes, your code is working for me. Thanks for the help. upvote from my side – user9437856 Apr 13 '20 at 08:25
  • Please update the background image answer in this... so that I can refer in future. – user9437856 Apr 13 '20 at 08:26
  • 1
    sure - yes, i have updated the code in the sandbox ... the same link in the answer has updated working code.... – gdh Apr 13 '20 at 08:31
0

Take a look at this answer.

If using webpack, you can use require.context to import an entire folder (./myImageFolder) of image files to match a regex (/\.(png|jpe?g|svg)$/) and then render them all with JSX from your react component.

import React from 'react';

function Images() {
  const images = importAll(require.context('./myImageFolder', false, /\.(png|jpe?g|svg)$/))

  return (
    <>
      {images.map(image => <img src={image} alt="" /> )}
    </>
  );
}

export default Images;


function importAll(r) {
  return r.keys().map(r);
}
ksav
  • 20,015
  • 6
  • 46
  • 66