I have a nextjs app which shows movies and their posters from an api and I am trying to add a blur effect to all images before they are fully loaded to be displayed. I found this comment on github discussion which uses plaiceholder but I couldn't find a way to make it work for multiple images. Here is some of my codes
// index.js
...
return (
<>
<MovieList data={props.data.trending} title="Trending Right Now" />
<MovieList data={props.data.popular} title="Popular" />
</>
);
export async function getStaticProps() {
var promises = [];
const api_key = '...'; // don't worry about api key I can make another one
const urls = [
`https://api.themoviedb.org/3/trending/movie/week?api_key=${api_key}`,
`https://api.themoviedb.org/3/movie/popular?api_key=${api_key}&language=en-US&page=1`
];
urls.forEach(function(url) {
promises.push(
axios.get(url).then(
function(data) {
return { success: true, data: data };
},
function() {
return { success: false };
}
)
);
});
const [trendingRes, popularRes] = await Promise.all(promises);
const trending = trendingRes.success === false ? null : trendingRes.data.data;
const popular = popularRes.success === false ? null : popularRes.data.data;
return { props: { data: { trending, popular } } };
}
// MovieList.js
{props.data
? props.data.results.map((movie, index) => {
return (
<>
...
<div>
<Image
src={`https://image.tmdb.org/t/p/w500${movie.poster_path}`}
alt="movie poster"
width="260"
height="391"
placeholder="blur" // doesn't work
/>
</div>
</>
);
})
: 'Not found'}
You can see full code here
You can provide a blurDataURL
prop when using dynamic images to be blurred.
When parsing the data received from the API in getStaticProps
, convert the images to base64 using plaiceholder
.
// index.js - getStaticProps
const [trendingRes, popularRes] = await Promise.all(
urls.map((url) =>
axios.get(url).then(
(data) =>
Promise.all(
data.data.results.map((one) => {
return getPlaiceholder(`https://image.tmdb.org/t/p/w500${one.poster_path}`)
.then(({ base64, img }) => {
return { ...one, img, base64 };
})
.catch(() => ({ ...one, img: null, base64: null }));
})
)
.then(
(values) => ({ success: true, data: values })),
() => ({ success: false })
)
)
).then((data) => data);
)
Then in your MovieList
component, use blurDataURL
in conjunction with placeholder="blur"
.
// MovieList.js
{props.data &&
props.data.map((movie, index) => {
return (
<>
<div>
<Image
src={movie.img}
alt="movie poster"
width="260"
height="391"
placeholder="blur"
blurDataURL={movie.base64}
/>
</div>
</>
);
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With