Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Flow type for React render method?

I'm curious what the proper Flow annotation is for both render methods in React classes, and simple returns in stateless functions:

const UserProfilePage = () => {
  return <div className="container page">
    <UserProfileContainer />
  </div>
};

By setting the return type intentionally incorrect (to a number), I got this error:

  8:   return <div className="container page">
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ React element: `div`
  8:   return <div className="container page">
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ React$Element. This type is incompatible with the expected return type of
  7: const UserProfilePage = (): number => {
                                 ^^^^^^ number

So, changing the code to this seems to satisfy Flow:

const UserProfilePage = (): React$Element => {
  return <div className="container page">
    <UserProfileContainer />
  </div>
};

I'm wondering if this is correct, and if so, where is this documented?

like image 463
ffxsam Avatar asked Jun 30 '16 21:06

ffxsam


People also ask

What is the flow of React?

Flow is a static type checker for your JavaScript code. It is developed at Facebook and is often used with React. It lets you annotate the variables, functions, and React components with a special type syntax, and catch mistakes early. You can read an introduction to Flow to learn its basics.

What render method do in React?

The Render Function The ReactDOM. render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.

What is React Native flow?

Flow is a framework that, like TypeScript, promotes static typing in JavaScript. And like TypeScript it ships with React Native without any issues.

What is the type of React element?

ReactElement is the type for elements in React, either created via JSX or React. createElement. ReactNode is wider, it can be text, number, boolean, null, undefined, a portal, a ReactElement, or an array of ReactNodes. It represents anything that React can render.


1 Answers

You don't need to annotate the render method, Flow should be able to infer the output type because it knows what JSX desugars to.

Flow has a built-in React interface, where all this stuff is defined:

declare class React$Element<Config> {
  type: ReactClass<Config>;
  props: $PropsOf<Config>;
  key: ?string;
  ref: any;
}

And then

render(): ?React$Element<any>;

So if you want to provide an explicit return type of a render method, you can use that signature. Well, maybe without a question mark if know you're not returning null. Not sure if there's any effect to omitting <any>.

like image 96
Nikita Avatar answered Oct 22 '22 23:10

Nikita