Home > Software engineering >  What is the type of a function component in React?
What is the type of a function component in React?

Time:06-06

I'm using React with TypeScript, and have two function components:

  1. List which represents a list of things
  2. Lists which renders all the lists given to it inside a <ul>

This is how I want to define Lists:

export function List() { ... }

export interface IListsProps {
    lists: List[];
}

export default function Lists({ lists }: IListsProps) { ... }

If List were a class component, this would have worked. But since List is a function component, TypeScript rejects this. What is the type of List here so that I can use it inside IListsProps? I don't want to use a generic any, or JSX.Element type.

CodePudding user response:

I would recommend using another name for your List component as it is a default Type already you could use typeof instead, but it is irritation IMHO.

export function List() { 

}

export interface IListsProps {
    lists: typeof List[];
}

export default function Lists({ lists }: IListsProps) { 
    
}

CodePudding user response:

Well, you will need to make an interface for your list object.

For example

export interface employee = {
 id: number,
 name: string,
 status: string
};

after that, you can import the object type into your component and define it for the props type.

  • Related