Trailing and leading commas added issue
I am calling a function from jsx as xyz(id)
inside the <img src = "xyz(id)" />
. In the calling function, I am retrieving the image value through a map as
const xyz = (id) =>{
return abc.map(a => {
if(a.id === id){
if(a.url){
return a.url;
}
}
})
}
When I inspect the img element trailing and leading commas are being appended after the return statement as "..returned_url..".
You need to only return the url part to the caller if there's a match - you need to exclude the empty results from the .map
callback, else they'll appear as empty strings between lots of commas.
const xyz = (id) => {
return abc
.map(a => {
if (a.id === id && a.url) {
return a.url;
}
})
.filter(Boolean);
}
But returning an array when you're trying to set a src
doesn't make much sense. If there's only one possible matching item, using .find
might be more appropriate than .map
, perhaps
const xyz = (id) => {
return abc
.find(a => a.id === id)
?.url;
}