Reputation: 7
I'm using a pixabay array. I did manage to get the data from my array, but the data contains 20 random pictures. I only want 3 pictures to be seen on my website.
I have used a slice array. Sadly it doesn't work for me, I think I did something wrong. --> Remove items from array with splice in for loop maybe I should use an if function?
This is my code:
{apiImages.map( img => (
<Card shadow={5} style={{minWidth: '450', margin: 'auto'}}>
<a href="/alleblogs">
<CardTitle style={{color: '#fff', height: '176px', background: 'url( { } ) center / cover' }}>Golden Bridge</CardTitle>
<CardText>
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Facilis distinctio esse qui eos, ad provident,
</CardText>
<CardActions border>
<Button style={{color: '#8dd5e8'}}>Likes:</Button>
<Button style={{color: '#8dd5e8'}}>Share</Button>
</CardActions>
</a></Card>
))}
As you can see I've used a loop. This loop only shows 20 cards (no pictures) but my problem is that I only want 3 cards to be shown.
{apiImages.splice(6).map( img => ---> This doesn't work either.
I don't know but maybe this code will be useful too (This is where I fetch my api):
componentDidMount() {
fetch("https://pixabay.com/api/?key=11095386-871fd43c33a92700d9bffb82d&q=travel&image_type=photo&pretty=true")
.then(res => res.json())
.then(
(result) => {
console.log(result)
this.setState({
apiImg: result.hits
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
Upvotes: 0
Views: 261
Reputation: 217
I recommend using slice
method that doesn't modify your initial array apiImages
:
// create a const that store first 3 images
const firstThreeImages = apiImages.slice(0, 3);
// render them
{firstThreeImages.map(img => //rendering )}
Upvotes: 1
Reputation: 1896
You can directly slice your array using Array.slice
.
var a = [1,2,3,4,5,6,7,22,34,43,56]
a.slice(0, 3).map((v) => { console.log('Element:', v) })
{apiImages.slice(0, 3).map( img => ---> This will work.
Upvotes: 1