reactjstypescriptnext.js

How to type a page component with props in Next.js?


I'm looking to correctly annotate the Home function component's parameters, but am running into a little bit of trouble. I was hoping to annotate it like: { events }: { events: Event[] }, but am getting the TypeScript error, Property 'events' does not exist on type '{ children: ReactNode }' in Next.js.

Next does a lot of wizardry behind the scenes, so I am not sure how I can fix this. Any ideas?

import type { NextPage } from 'next';
import { GetServerSideProps } from 'next';
import axios from '../lib/axios';

import { Event } from '../ts/interfaces';

const Home: NextPage = ({ events }) => {
  return (
    <div>
      {events.map((event: Event) => (
        <div key={event.title}>{event.title}</div>
      ))}
    </div>
  );
};

export const getServerSideProps: GetServerSideProps = async () => {
  const res = await axios.get<Event[]>(`${process.env.API_URL}/events`);

  return {
    props: { events: res.data },
  };
};

export default Home;

Solution

  • You need to pass the Home props type (in your case { events: Event[] }) as the generic type to NextPage.

    import { Event } from '../ts/interfaces';
    
    const Home: NextPage<{ events: Event[] }> = ({ events }) => {
        return (
            <div>
                {events.map((event: Event) => (
                    <div key={event.title}>{event.title}</div>
                ))}
            </div>
        );
    };