1
I want to turn the following class into a function:
class Basic extends Component<Props, State>
My question is: how do I move the props and state properties to the function?
1
I want to turn the following class into a function:
class Basic extends Component<Props, State>
My question is: how do I move the props and state properties to the function?
2
props
Like props
are passed as the first parameter for functional components by React, just put the appropriate types for the first parameter. Generally, one creates a interface
for that reason:
import React from 'react';
interface Props {
name: string;
age: number;
}
export function UserCard(props: Props) {
return <>{/* ... */}</>;
}
You can also use the type React.FC
, exported by React:
import React from 'react';
interface Props {
name: string;
age: number;
}
export const UserCard: React.FC<Props> = (props) => {
return <>{/* ... */}</>;
};
However, by personal preference, I prefer not to use Arrow functions for this kind of thing. As can be verified in this answer, components with function statements have some advantages compared to Arrow functions.
state
How the state in functional components is achieved through the React Hooks, you do not add the state types directly into the component function, but into the hooks' own calls. Most of the time, this is done with generic.
Usually, the React API hooks automatically infer the state type through the first argument. See how to pass an explicit type to a useState
, for example:
import React, { useState } from 'react';
export function MyComponent() {
const [bool, setBool] = useState<boolean>(false);
setBool(true); // ok
setBool('foo'); // Argument of type '"foo"' is not assignable to parameter of type 'SetStateAction<boolean>'.
return <code>{bool.toString()}</code>
}
See the example above in Typescript playground.
There is currently no explanation in the React documentation of how to use these generics. However, you can check the Type settings for React on Github.
Browser other questions tagged javascript typescript react
You are not signed in. Login or sign up in order to post.
you are using
typescript
?– novic
Yes, but I don’t understand almost anything
– krolgon
The state in functional components is not tied to the function instance, so there is no reason to type the state in the function, as is done in the classes. Try [Edit] your question to add more information?
– Luiz Felipe
@Luizfelipe indirectly yes ...I can type the state.
– novic
@Virgilionovic, yes, you can type the state, but the state type is not tied to the function instance (just as it is for the classes)...
– Luiz Felipe