D
D
dmitriu2562020-11-13 14:17:09
React
dmitriu256, 2020-11-13 14:17:09

How to correctly load dynamic images in a child component?

I've asked a similar question before, but couldn't find a definitive answer.
The site is static - built to practice with the basics of React.
Essence of the question
There is a main component Features in it state with an array of data blocks for the child component

How to correctly pass the path to the image to the child component, is my approach to solving the problem correct?

The working method for me
The project is built through create-react-app
1) In order not to violate the concept of react, I save all images in the src/shared/img folder and not in the public folder
2) In the child component, I created a "library file" that stores everything in itself paths to the images I need

import img1 from '../../../shared/img/features/block1.png';
import img2 from '../../../shared/img/features/block2.png';
import img3 from '../../../shared/img/features/block3.png';
import img4 from '../../../shared/img/features/block4.png';
import img5 from '../../../shared/img/features/block5.png';
import img6 from '../../../shared/img/features/block6.png';

export {img1, img2, img3, img4, img5, img6};

3) In FeaturesItem I connect my image library. I write the path to the image in the img tag as an array, The result of manipulations is the State of the main Features component
import * as Img from './images';
<img src={Img[`${props.img}`]} alt={props.alt}/>
5fae676d08eaa491403037.png

import FeaturesItem from "./FeaturesItem/FeaturesItem";
export default class Features extends React.Component{
    constructor(props) {
        super(props);

        this.state = {
           
            blocks: [
              
                {
                    img: 'img1',
                    alt: 'Производство',
                    title: 'Производство',
                    descr: '4 технологические линии способны выполнить любой заказ любой сложности'
                },
         
                {
                    img: 'img2',
                    alt: 'Бесплатные образцы',
                    title: 'Бесплатные образцы',
                    descr: ' Бесплатно делаем образцы гофроупаковки - это помогает заранее увидеть\n' +
                        '                                        упаковку'
                },
               ... 
        ]};
render(){
<div className="row">

                        {this.state.blocks.map((block, index) => {
                            return (
                                <FeaturesItem
                                    key={index}
                                    img={block.img}
                                    alt={block.alt}
                                    title={block.title}
                                    descr={block.desc}
                                />
                            );
                        })}

                    </div>
}

The connection methods that I tried before creating the connection library - the result is negative - :

//1
 <img src={props.img} alt={props.alt}/>
//2
 <img src={require(props.img)} alt={props.alt}/>


Having gone through different methods of connecting images to the component, I came to the following conclusions:
1) This approach is valid only for static sites - where the exact number of images is known and all of them are manually registered in the library file

2) In real projects - where the number of images is unknown and write down the path to each picture is not the best solution. To do this, the path to the image that is stored on the server will be passed to the state from componentDidMount - ajax request.

Summary
Static elements on the site are connected via import.

In dynamic sites (news card, product card) we use data from the server - we get rid of manual prescribing of paths to files.
<img src={props.img} alt={props.alt}/>

How correct is my approach to solving the problem, and are the arguments on the topic of connecting files correct?

Answer the question

In order to leave comments, you need to log in

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

This approach is valid only for static sites - where the exact number of images is known and all of them are manually registered in the library file

That's right, when using images as modules (and when importing and building through webpack, this is exactly the case, images actually become js modules).
) In real projects - where the number of images is unknown and writing down the path to each image is not the best solution. To do this, the path to the image that is stored on the server will be passed to the state from componentDidMount - ajax request.

When using dynamic images, the paths and the images themselves become not static, but data. That is, you need to work with them as with data. In general, these paths must be received from the backend along with the data request.
In the end, yes, that's right. import is when these are static files. In the case of dynamic paths to images go to the data model.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question