Next JS Course
Next JS provides built-in support for image optimization with the next/image component. This component automatically optimizes images on-demand as they are requested, improving performance and loading times for your application.
Basic Usage
The next/image component is used to display images in a Next JS application. It provides features like lazy loading, responsive images, and automatic resizing.
Lets see an example,
import React, { useEffect } from 'react'; import Image from 'next/image'; const AboutMe: React.FC = () => { useEffect(() => { document.title = `POAbout Me`; }, []); return ( <div className="container mt-5 aboutme-container"> <div className="row"> <div className="col-md-4"> <Image src="/images/praveenoruganti.JPG" width={300} height={300} className="img-fluid rounded-circle mb-3" alt="Praveen Oruganti" priority={true} /> </div> <div className="col-md-8 custom-class"> <h2>About Me</h2> <p> I am Praveen Oruganti, a Technical Architect, Tech Blogger, and an Educator with over 16 years of experience in IT, based in Hyderabad, Telangana, India. I specialize in designing and implementing efficient software solutions across various industries. </p> </div> </div> </div> ); }; export default AboutMe;
Remote Images
Next JS allows you to optimize images from remote sources by configuring the next.config.js file.
// next.config.js module.exports = { images: { domains: ['a.travel-assets.com'], }, };
<Image src="https://a.travel-assets.com/mad-service/header/takeover/expedia_marquee_refresh.jpg" width={500} height={500} />
Image Loader
If you need custom image handling, you can use the loader prop to define a custom image loader.
// Custom image loader function const customLoader = ({ src, width, quality }) => { return `https://example.com/${src}?w=${width}&q=${quality || 75}`; }; <Image loader={customLoader} src="/path/to/your/image.jpg" alt="Custom Loader Image" width={800} height={600} />
Placeholder Images
Next JS supports blurred placeholders while the main image is loading.
<Image src="/path/to/your/image.jpg" alt="Blur Placeholder Image" width={800} height={600} placeholder="blur" blurDataURL="/path/to/placeholder.jpg" // Path to a low-quality placeholder image />
Image CDN
Next JS can be configured to use an external image CDN for serving optimized images.
// next.config.js module.exports = { images: { loader: 'imgix', // or 'cloudinary', 'akamai' path: 'https://example.imgix.net/', // The base URL of your CDN }, };