I'm trying to dynamically import some images in one of my react components. The names of the images are stored in a JSON file which are then being passed to the component as a prop.
This is the parent component where the data is being passed in:
const GridBlocks = gridItems.map(({ imageSrc, alt, ...textProps }, index) => (
<div key={`grid-section-${index}`} styleName="grid-section">
<ImageBlock imageSrc={imageSrc} alt={alt} />
<TextBlock {...textProps} />
</div>
));
Now the problem I'm facing is that obviously I cant just
import prop from 'bar'
as usual since the child component won't have a clue what 'prop' is.
I've had a look around and I think the solution should look something like this? (except y'know....working). Particularly around 'require.context' but I just can't figure out the implementation.
import React from 'react';
import PropTypes from 'prop-types';
import './ImageBlock.css';
const assetRequire = require.context('Images/howItWorks/', true, /\.(png|jpg|svg)$/);
const ImageBlock = async ({ imageSrc, alt }) => {
const imageSrc1x = assetRequire(`${imageSrc}.png`);
const imageSrc2x = assetRequire(`${imageSrc}@2x.png`);
return (
<img
src={imageSrc1x}
srcSet={`${imageSrc1x} 1x, ${imageSrc2x} 2x`}
alt={alt}
styleName="image-block"
/>
);
};
ImageBlock.propTypes = {
imageSrc: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
};
export default ImageBlock;
Any help would be greatly appreciated.