`` I'm loading a JSON object from an API and deserializing it into an array of objects
the array has a property for the image name, in react I need to match the JSON object property name to that of the relevant required image
example :
const foo = require("./images/foo.png");
const bar = require("./images/bar.png");
const loo = require("./images/loo.png");
const mee = require("./images/mee.png");
const foo: myObjectArray[] = useFetchCustomAPIHook()
/* data example:
const foo = {
"images":
[
{ "id": 1, "name": "foo.png" },
{ "id": 2, "name": "bar.png" },
{ "id": 3, "name": "loo.png" },
{ "id": 4, "name": "mee.png" }
]
};
*/
foo.every((item:any) => {
/* TO DO: Match name to relevant required item */
// Pseudo :
// match item.name to relevant const e.g. foo || bar || loo || mee etc
})
because require adds cache busting the names are './images/foo.fbcb91799ceba75b2e3a.png'
I could use a regex but it would have to match test all const required items against the given item for every iteration
foo.every((item:any) => {
const t1 = foo.match(/[^\\/]+?(?=\.{1}\w){1}\b/i)[0]
const t2 = bar.match(/[^\\/]+?(?=\.{1}\w){1}\b/i)[0]
const t3 = loo.match(/[^\\/]+?(?=\.{1}\w){1}\b/i)[0]
if(t1 === item.name){
item.name = t1
}else if( t2 === item.name){
item.name = t2
}else ....
Also, there are other places in the code that update the array and set its property name to different images...so I tried using
const foo = "foo.png";
const bar = "bar.png";
const loo = "loo.png";
const mee = "mee.png";`
and then in the HTML render, I called the required method to load the image like so:
function loadImage(content: any): string {
if (content) {
return require(`./images/${content}`)
}
return ''
}
...
return (
<>
<div>
{foo.map((item: any, index: number) => {
return (
<div key={index}>
<img
data-cell-id={item.index}
data-cell-index={index}
alt={loadImage(item?.name)}
src={loadImage(item?.name)}
/>
</div>
);
})}
</div>
</>
);
This works for the first required const item but as soon as a different item is passed to the function where the name is for a different image it throws an error:
Cannot find module './/assets/images/bar.png'
But if I change the consts so that const foo = 'bar.png'
and bar const = 'foo.png'
then it throws
Cannot find module './/assets/images/foo.png'
So it's not that it can't find the image but rather that as soon as the image is different it fails but I'm not entirely sure why?
Hope I explained this properly, all the above code is mostly Pseudo'ish so it might not run, it's just to give the general idea