So i have an array that has many file types. These are all under array.contentType. What i want, is to just have it return images, so array.contentType.images? i think.
Here is the code:
const renderSlides = attachmentInfo.map((item,index) => (
<div key={index}>
{item.contentType === 'image/jpeg' ? <img src={item.url} /> : ''}
<p className="legend">{item.name}</p>
</div>
));
My guess is i need to change the .map to .filter, but i’ve never used .filter. And from what i’ve read online its a bit confusing. The ternary works, but it returns a blank screen in my carousel slide for everything that isn’t an image. What i want is JUST the images.
>Solution :
Array.filter produces a new array where items match the predicate (function returning a boolean) provided.
For example:
console.log([-1, 0, 1, 2, 3].filter(x => x >= 1));
would result in the value:
[1, 2, 3]
A filter method call will have to be placed in front of the call to the map method. Additionally, all images have a content type starting with "image/", so checking for images can be generalized as well. Putting these both together would result in the following code:
const renderSlides = attachmentInfo.filter(({contentType}) =>
contentType.startsWith('image/')
).map((item,index) =>
<div key={index}>
<img src={item.url} />
<p className="legend">{item.name}</p>
</div>
);