Next JS Practice Exercises: Essential Techniques for Mastering the Framework

Here is a short practice on Next.js:

  1. Create a new directory for your Next.js project and navigate into it.
perlCopy codemkdir my-next-app && cd my-next-app
  1. Initialize a new Next.js project by running the following command:
csharpCopy codenpm init -y
  1. Install the necessary dependencies by running the following command:
pythonCopy codenpm install next react react-dom
  1. 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;
  1. Start the Next.js development server by running the following command:
Copy codenpm run dev
  1. Open your browser and navigate to http://localhost:3000 to see your “Hello, World!” page.
  2. 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;
  1. Import the Header component in your pages/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;
  1. 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.

Tags: No tags

Add a Comment

Your email address will not be published. Required fields are marked *