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>;
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With