Class change to function

Asked

Viewed 165 times

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

    you are using typescript?

  • Yes, but I don’t understand almost anything

  • 1

    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?

  • @Luizfelipe indirectly yes ...I can type the state.

  • @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)...

1 answer

2


Tipando 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.


Tipando 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

You are not signed in. Login or sign up in order to post.