Here is a short practice on Next.js:
- Create a new directory for your Next.js project and navigate into it.
perlCopy codemkdir my-next-app && cd my-next-app
- Initialize a new Next.js project by running the following command:
csharpCopy codenpm init -y
- Install the necessary dependencies by running the following command:
pythonCopy codenpm install next react react-dom
- Create a new file named
pages/index.js
and add the following code to create a simple “Hello, World!” page:
javascriptCopy codeimport React from 'react';
function HomePage() {
return <h1>Hello, World!</h1>;
}
export default HomePage;
- Start the Next.js development server by running the following command:
Copy codenpm run dev
- Open your browser and navigate to
http://localhost:3000
to see your “Hello, World!” page. - Create a new component in a separate file, for example,
components/Header.js
. Add the following code to create a header component:
javascriptCopy codeimport React from 'react';
function Header() {
return (
<header>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
);
}
export default Header;
- Import the
Header
component in yourpages/index.js
file and use it in your page:
javascriptCopy codeimport React from 'react';
import Header from '../components/Header';
function HomePage() {
return (
<>
<Header />
<h1>Hello, World!</h1>
</>
);
}
export default HomePage;
- Restart the Next.js development server and refresh your browser to see the header component displayed on the page.
This is a simple example of how to create a Next.js application and add a custom component to it. You can continue to build on this example and explore the features of Next.js by adding additional pages, fetching data, and creating dynamic routes.