Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Flow return type of a React stateless functional component?

If I have something like this

const RandomComponent = (props) => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent type={props.type} />
  </div>
)

how will I type annotate the return type with Flow, i.e., what should replace /* ??? */ in the code below?

const RandomComponent = (props: { id: string, vino: number): /* ??? */ => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)

Edit: This is what the Flow docs has to say about stateless functional components. I may be blind, but I can't see anything about a return type there, only prop types.

like image 653
ahstro Avatar asked Nov 03 '16 07:11

ahstro


2 Answers

The return type of a pure component (which is the same type of the render function of a normal component) is ?React$Element<any>.

As you can read in its definition React$Element has a type parameter Config which is not very useful per se and it's there only for consistency with the definition of ReactClass.

So your definition can be written as

const RandomComponent = (props: { id: string, vino: number }): React$Element<any> => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)

or if you prefer

import type { Element } from 'react'

const RandomComponent = (props: { id: string, vino: number }): Element<any> => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)

or even

import React from 'react'

const RandomComponent = (props: { id: string, vino: number }): React.Element<any> => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)
like image 137
Gabriele Petronella Avatar answered Sep 28 '22 16:09

Gabriele Petronella


Turns out it's React.Element, which is a polymorphic type (which I'm not 100% sure what it means), so the correct (enough) code would be

const RandomComponent = (props: { id: string, vino: number): React.Element<*> => (
  <div>
    <SomeSubComponent id={props.id} />
    <AnotherSubComponent veryImportantNumber={props.vino} />
  </div>
)
like image 43
ahstro Avatar answered Sep 28 '22 15:09

ahstro