D
D
dmitriu2562020-11-11 14:37:10
React
dmitriu256, 2020-11-11 14:37:10

Why is img not connected via require?

Why is img not connected via require?
Images are stored in the src/shared/img folder. I

used four methods for including an image:

//1 метод
import myImg from './main-img.png';

//2 метод - не работает
//const myImg = require('./main-img.png');

export default class Main extends React.Component{
    render() {
        return (
            <section className="main dark-bg" id="main">
                <div className="container">
                    <div className="row">
                        <div className="col-12 col-md-12 col-lg-5 hidden-mobile hidden-sm hidden-md">
                            <div className="main-img wow zoomIn" data-wow-duration="2s" data-wow-delay="0.1">
                                {/*<img src={myImg} alt="Main Box"/>*/}

                                {/*3 метод*/}
                                <img src={require('./main-img.png')} alt="Main Box"/>

 {/*4 метод*/}
                                <img src="./main-img.png" alt="Main Box"/>

                            </div>
                            {/* /.main-img */}
/// остальной программный  код


When I connect the image via import, everything works fine . Why methods 2 and 3 do not work - there are no errors
- as well as the image itself
. images are initially stored in the public / img folder In JSX Displayed as needed, but if you set the background of the section through SASS like5fabca97710a9198154412.png


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

5fabcaa031dfb575374795.png

<img src="/img/main/main-img.png" alt="Main Box"/>

.main
  padding-top: 65px
  padding-bottom: 78px
  color: $text-color-light
  background: $text-color-dark url("/img/main/main-bg.jpg") center 0 no-repeat


I get an error - that you can not go beyond the src directory

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twolegs, 2020-11-11
@dmitriu256

This solution is not very good, since webpack does not know what resources to copy (you import them dynamically).
Possible solution:
Import all required images. Next, you can create a dictionary and use the values ​​from the dictionary in your code.

import Img1 from './img1.png';
import Img2 from './img1.png';
import Img3 from './img1.png';

export const images = { Img1, Img2: Img3 }

And when using:
import { images } from 'assets.js';

<ImgComponent src={images.Img1} />

The webpack loader converts image files to relative paths, so you don't have to be afraid of static imports of these files. In fact, the resource will only be loaded when this path gets into src.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question