'Add additional props to component in a foreach loop
i have a component in React that receives some elements (photos), i have a object with this composition:
getItems() {
const { gallery } = this.props;
const { content_elements: contentElements } = gallery;
const items = [];
if (contentElements) {
contentElements.forEach((photo, index) => {
let item = (
<div key={photo.id} className="gal__fig-item">
<Image
srcset="gallery"
figureClassName="mm"
imgClassName="mm__img"
noZoom={true}
showCaption={false}
wrapperClassName="mm__wr"
{...photo}/>
</div>
);
items.push(item);
});
}
return items;
}
I need to add a prop in the image component, but only in the first element (index = 0).
I do this:
getItems() {
const { gallery } = this.props;
const { content_elements: contentElements } = gallery;
const items = [];
if (contentElements) {
contentElements.forEach((photo, index) => {
let item = (
<div key={photo.id} className="gal__fig-item">
<Image
srcset="gallery"
figureClassName="mm"
imgClassName="mm__img"
noZoom={true}
showCaption={false}
wrapperClassName="mm__wr"
{...photo}/>
</div>
);
if(index === 0){
item = (
<div key={photo.id} className="gal__fig-item">
<Image
srcset="gallery"
figureClassName="mm"
imgClassName="mm__img"
noZoom={true}
showCaption={false}
hasLazyLoad={false}
wrapperClassName="mm__wr"
{...photo}/>
</div>
);
}
items.push(item);
});
}
return items;
}
That works, but....maybe there is an other option, more clean code, to do it? Someone can help me? Thanks
Solution 1:[1]
you can set hasLazyLoad based on the value of i:
if (contentElements) {
contentElements.forEach((photo, index) => {
let item = (
<div key={photo.id} className="gal__fig-item">
<Image
srcset="gallery"
figureClassName="mm"
imgClassName="mm__img"
noZoom={true}
showCaption={false}
hasLazyLoad={i !== 0} // use i !== 0 to false when i = 0
wrapperClassName="mm__wr"
{...photo}/>
</div>
);
}
```
Solution 2:[2]
I would replace forEach to map and add ternary operator for hasLazoLoad prop:
getItems() {
const { gallery } = this.props;
const { content_elements: contentElements } = gallery;
const items = contentElements?.map((photo, index) => {
return <div key={photo.id} className="gal__fig-item">
<Image
srcset="gallery"
figureClassName="mm"
imgClassName="mm__img"
noZoom={true}
showCaption={false}
hasLazyLoad={index === 0 ? false : true}
wrapperClassName="mm__wr"
{...photo} />
</div>
}) || [];
return items;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jolo |
| Solution 2 | Oro |
