What would the return type be here?
const Foo : () => // ??? = () => ( <div> Foobar </div> )
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 .
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.
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.
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.
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; }
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
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