Reputation: 145
I am trying to select the first path directory from the api that includes an Image so I can set the value to the Image source and display the first image but when i use fl[0] i get all values
here is the code :
{useLesson &&
useLesson.files.map((fl, index) => {
if (fl.mimetype.includes("image")) {
// this always get all values not only the first value
console.log(fl[0])
// and this always gives me infinite loop issue
setSelectedImage(fl[0])
return (
<div key={index}>
<img src={axiosUse + fl.path} alt="" />
</div>
)
}
})
}
How can I get only the first value from a map that includes something inside it ?
what I am trying to do is getting files from the server and if its an image file then display some component but how can I get only the first Image value file ?
Upvotes: 1
Views: 391
Reputation: 196026
You could create a new component to show the first file
const FilePreview = ({ mimetype, files, basepath }) => {
const firstFileOfType = files.find((file) =>
file.mimetype.includes(mimetype)
);
if (!firstFileOfType) return null;
return (
<div>
<img src={basepath + firstFileOfType.path} alt="" />
</div>
);
};
and use it as
{useLesson && (
<FilePreview
mimetype="image"
files={useLesson.files}
basepath={axiosUse}
/>
)}
Upvotes: 2