Other NextJS Features
Other NextJS Features
Add head content
To add head content to a NextJS page, we can use the Head
component from the next/head
package. Here's an example:
import Head from 'next/head';
function MyPage() {
return (
<div>
<Head>
<title>My Page Title</title>
<meta name="description" content="My page description" />
</Head>
<h1>My Page Content</h1>
</div>
);
}
In this example, we've added a Head
component with a title
and meta
tag for the page description. The title
tag sets the title of the page in the browser tab, and the meta
tag provides a description for search engines. The content
attribute of the meta
tag sets the description text.
_app.js
To add head content to all pages in a NextJS app, we can create a custom _app.js
file in the pages
directory. Here's an example:
import Head from 'next/head';
function MyApp({ Component, pageProps }) {
return (
<div>
<Head>
<title>My App Title</title>
<meta name="description" content="My app description" />
</Head>
<Component {...pageProps} />
</div>
);
}
export default MyApp;
In this example, we've added a Head
component to the MyApp
component, which wraps all pages in the app. We've set the title
and meta
tags for the app as well. This will apply the same head content to all pages in the app.
_document.js
To add head content to all pages in a NextJS app, we can create a custom _document.js
file in the pages
directory. Here's an example:
import Document, { Html, Head, Main, NextScript } from 'next/document';
class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<title>My Document Title</title>
<meta name="description" content="My document description" />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
export default MyDocument;
Optimizing Images
To optimize images for the web, we can use the next/image
component. This component automatically optimizes images and provides lazy loading and responsive images. Here's an example:
import Image from 'next/image';
function MyPage() {
return (
<div>
<h1>My Page Content</h1>
<Image src="/my-image.jpg" alt="My Image" width={500} height={500} />
</div>
);
}
In this example, we've imported the Image
component from next/image
and used it to display an image with a width of 500px and a height of 500px. The src
attribute specifies the path to the image, and the alt
attribute provides a text description of the image for accessibility purposes. The width
and height
attributes are optional, but can help improve page load times and reduce bandwidth usage.