create new route in nextjs in typescript

To create a new route in Next.js in TypeScript, you can define a new page component in the /pages folder with the desired pathname. For example, to create a new route with the path /about, create a file /pages/about.tsx.

In this file, define a React component that represents the page to be rendered when the route is accessed. This component should export a default function that returns the JSX that should be rendered.

index.ts
import React from 'react';

export default function AboutPage() {
  return (
    <div>
      <h1>About Page</h1>
      <p>This is the about page content.</p>
    </div>
  );
}
176 chars
11 lines

With this setup, the /about route will render this component.

Note that if you want to pass parameters in the URL, you can use dynamic routes. For example, if you want to create a route with the path /users/:id, where id is a dynamic parameter, you can create a file /pages/users/[id].tsx. In this file, you can access the id parameter using the useRouter hook from next/router.

index.ts
import React from 'react';
import { useRouter } from 'next/router';

export default function UserPage() {
  const router = useRouter();
  const { id } = router.query;

  return (
    <div>
      <h1>User Page {id}</h1>
      <p>This is the user page content for user {id}.</p>
    </div>
  );
}
295 chars
15 lines

related categories

gistlibby LogSnag