Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the correct type for a React instance of a component in typescript

Say I have a component that takes 2 button instances:

export interface GridProps {
  backButton: any;
  nextButton: any;
}

Should the type for the button be React.ReactNode or React.ReactElement

so either:

export interface GridProps {
  backButton: React.ReactNode;
  nextButton: React.ReactNode;
}

or

export interface GridProps {
  backButton: React.ReactElement<any>;
  nextButton: React.ReactElement<any>;
}
like image 731
dagda1 Avatar asked Dec 20 '17 06:12

dagda1


People also ask

What is type of React component in TypeScript?

React components can greatly benefit from TypeScript. Typing components is especially useful to validate the component props. Usually, that's performed by defining an interface where each prop has its type. Then, when the annotated component renders, TypeScript verifies if correct prop values were supplied.

What is the type of a React component?

Components serve the same purpose as JavaScript functions, but work individually to return JSX code as elements for our UI. Components usually come in two types, functional components and class components, but today we will also be talking about pure components and higher-order components.

What is an instance of a React component?

An instance is what you refer to as this in the component class you write. It is useful for storing local state and reacting to the lifecycle events. Function components don't have instances at all. Class components have instances, but you never need to create a component instance directly—React takes care of this.

What is the type of React props TypeScript?

React has its own, built-in way of type checking called “prop types”. Together with TypeScript this provides a full, end-to-end type-checking experience: Compiler and run-time.


1 Answers

React.ReactNode is more convenient way for passing markup to child components. It contains everything you can insert in JSX like <div>{passedContent}</div> It is used in many React component libraries. It makes sense to use React.ReactElement<any> only if you want to restrict customization to elements of particular class. For example React.ReactElement<ButtonProps>. It is useful if you want to clone passed element and append some props to it.

like image 154
Ilya Rezvov Avatar answered Oct 22 '22 15:10

Ilya Rezvov