mathclass
mathclass

Reputation: 3

React Native <{}> syntax

I created a new React Native project using react-native init and in the generated template, the main component class looks like this:

export default class App extends Component<{}> {
   ...
}

I don't really understand what the <{}> part means. I've never seen this before and all the examples seem to omit it. Just curious as to what its purpose is and if it's necessary.

Upvotes: 0

Views: 234

Answers (3)

Rajesh
Rajesh

Reputation: 24955

When you are using typescript, you have to specify the type of values to be expected. This allows detecting mismatching properties during compile time and reduces the amount of errors.

So when you do Component<{}>, {} is the type for Props, your component will receive.

This is how React's Component class looks like:

enter image description here

If you notice, the type is <P, S>, which stands for <Props, State>.


There is another interface called ComponentClass that has a signature <P>,

enter image description here

which initializes a new component internally with state as any. This interface is used in ReactElement's type:

enter image description here

So all in all, you are defining a Component which accepts no props and but can have state of any type. This is usually done when you are not sure about you component's interactions.

Ideally a component should look like this:

interface IComponentState {
  ...
}

interface IComponentProps {
  ...
}

export class MyComponent<IComponentProps, IComponentState> extends React.Component {
  ...
}

This enforces consumer to pass any necessary properties and enforces you to have proper value of state.

Upvotes: 2

gunn
gunn

Reputation: 9175

These are flow type annotations. See https://flow.org/ You'll notice that there's a @flow comment at the top of the file, and a .flowconfig file in the root of the project.

Using flow here is optional, but it can help you catch bugs.

Upvotes: 0

Daniel Khoroshko
Daniel Khoroshko

Reputation: 2721

This is either Typescript of Flow. You usually don't describe props as propTypes, but rather as interface or type. Then the type is passed to React.Component as a generic.

Type of props would be the passed type plus { children?: ReactNode }

Actually there are two generic arguments, second for State

Very useful and convenient stuff.

https://www.typescriptlang.org/docs/handbook/generics.html https://www.typescriptlang.org/docs/handbook/react-&-webpack.html

Upvotes: 0

Related Questions