I'm using material ui and next js. This is my code,
import { Container, Grid, Paper } from '@mui/material';
import { useState } from 'react';
import { styled } from '@mui/material/styles';
import ButtonBase from '@mui/material/ButtonBase';
import Link from 'next/link'
const Img = styled('img')({
margin: 'auto',
display: 'block',
maxWidth: '100%',
maxHeight: '100%',
});
const Home = (props) => {
const [albums, setAlbums] = useState([
{
"userId": 1,
"id": 1,
"title": "quidem molestiae enim",
"photos": {
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
},
{
"userId": 1,
"id": 2,
"title": "sunt qui excepturi placeat culpa",
"photos": {
"albumId": 2,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
},
{
"userId": 1,
"id": 3,
"title": "omnis laborum odio",
"photos": {
"albumId": 3,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
},
]);
return (
<div>
<Container sx={{ marginTop: '10px;' }}>
<Grid container spacing={2}>
{albums.map((item, key) => {
return (
<Grid key={key} item sm={6} xs={12}>
<Link href={`/album/${item.id}`}>
<Paper sm={{ textAlign: 'center' }} sx={{ p: 2, margin: 'auto', flexGrow: 1 }}>
<Grid container spacing={2}>
<Grid item>
{(undefined !== item['photos'] && item['photos'].length) &&
<ButtonBase sx={{ width: 128, height: 128 }}>
<Img alt="complex" src={item['photos'][0]['thumbnailUrl']} />
</ButtonBase>
}
</Grid>
</Grid>
</Paper>
</Link>
</Grid>
)
})}
</Grid>
</Container>
</div>
)
}
export default Home;
Here the link works fine but images are not loading. Is there any way to avoid that?
CodePudding user response:
Because photos
is not array but a object:
You try to get url of photo from array:
<Img alt="complex" src={item['photos'][0]['thumbnailUrl']} />
But in state you have photo an object:
...
"photos": {
"albumId": 1,
"id": 1,
"title": "accusamus beatae ad facilis cum similique qui sunt",
"url": "https://via.placeholder.com/600/92c952",
"thumbnailUrl": "https://via.placeholder.com/150/92c952"
},
...
Solution:
<Img alt="complex" src={item['photos']['thumbnailUrl']} />
OR:
<Img alt="complex" src={item.photos.thumbnailUrl} />