Answer the question
In order to leave comments, you need to log in
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};
import * as Img from './images';
<img src={Img[`${props.img}`]} alt={props.alt}/>
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>
}
//1
<img src={props.img} alt={props.alt}/>
//2
<img src={require(props.img)} alt={props.alt}/>
<img src={props.img} alt={props.alt}/>
Answer the question
In order to leave comments, you need to log in
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
) 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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question