Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the TypeScript return type of a React stateless component?

What would the return type be here?

const Foo   : () => // ???   = () => (     <div>       Foobar     </div>   ) 
like image 270
ahstro Avatar asked May 23 '17 11:05

ahstro


People also ask

What is the return type of a React component?

ReactNode Type in TypeScript The type is returned by React class components' render() function. It can be a ReactElement , ReactFragment , ReactText , a string, a Boolean, and other falsy values in JavaScript, such as undefined or null .

What is TypeScript type for React component?

Within TypeScript, React.Component is a generic type (aka React.Component<PropType, StateType> ), so you want to provide it with (optional) prop and state type parameters: type MyProps = { // using `interface` is also ok message: string; }; type MyState = { count: number; // like this }; class App extends React.

What is stateless component in React?

Stateless components are those components which don't have any state at all, which means you can't use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.

What is IntrinsicAttributes in TypeScript?

IntrinsicAttributes interface can be used to specify extra properties used by the JSX framework which are not generally used by the components' props or arguments - for instance key in React.


2 Answers

StatelessComponent type mentioned in this answer has been deprecated because after introducing the Hooks API they are not always stateless.

A function component is of type React.FunctionComponent and it has an alias React.FC to keep things nice and short.

It has one required property, a function, which will return a ReactElement or null. It has a few optional properties, such as propTypes, contextTypes, defaultProps and displayName.

Here's an example:

const MyFunctionComponent: React.FC = (): ReactElement => {   return <div>Hello, I am a function component</div> } 

And here are the types from @types/react 16.8.24:

type FC<P = {}> = FunctionComponent<P>;  interface FunctionComponent<P = {}> {     (props: PropsWithChildren<P>, context?: any): ReactElement | null;     propTypes?: WeakValidationMap<P>;     contextTypes?: ValidationMap<any>;     defaultProps?: Partial<P>;     displayName?: string; } 
like image 108
Timo Avatar answered Sep 28 '22 23:09

Timo


interface ISomeCoolInterface {    some: 'string';    cool: 'string';    props: 'string'  }      const SomeCoolComponent     : React.FC<ISomeCoolInterface>      = ({ some, cool, props }): JSX.Element => {         return <SomeCoolComponent>{some, cool, props}</SomeCoolComponent>           } 

The important bit here being the return type JSX.Element

like image 40
Vishal Sakaria Avatar answered Sep 28 '22 23:09

Vishal Sakaria