Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flowtype, React and defaultProps

After hours of searchs and tests, I didn't succeed to find any solution to make flow understand defaultProps

See Try Flow example

Using this model is unconsitent:

type PropsType = {|
  size?: 'small' | 'big',
|};


class Letter extends PureComponent<PropsType> {

  static defaultProps = {
    size: 'small',
  }

}

Thanks

Edit

After Tomasz Mularczyk's suggestion, I created another Try Flow example with:

type PropsType = {|
  size: 'small' | 'big',
|};

instead of

type PropsType = {|
  size?: 'small' | 'big',
|};

But

defaultProp size is not typed anymore:

static defaultProps = {
  size: 'BAD DEFAULT PROPS', // no error (?!)
}

Solution

See Tomasz Mularczyk's answer

+

Don't wait flow error on your current component ( in my case), but where it will be imported and declared.(seems semi-static no?)

like image 401
Made in Moon Avatar asked Apr 01 '18 13:04

Made in Moon


People also ask

Is React defaultProps deprecated?

Because defaultProps on functions will eventually get deprecated.

Should I use defaultProps React?

If you want the default values to be applied for every method, such as the ones from the React life-cycle ( shouldComponentUpdate , etc.) then you must use the defaultProps instead. So, the previous code is actually a mistake that may lead to misunderstanding about the default value of name .

What is defaultProps in React JS?

The defaultProps is a React component property that allows you to set default values for the props argument. If the prop property is passed, it will be changed. The defaultProps can be defined as a property on the component class itself, to set the default props for the class.

CAN node React to string?

React. Node can be null, a boolean, a number, a string, a React element, or an array of any of those types recursively. If you need a return type for your component render() methods then you should use React.


1 Answers

Just remove ? from size type. Flow will automatically see that you created defaultProps and will not require it.

From docs:

To type default props add a static defaultProps property to your class.

...

React also supports default props on stateless functional components. Similarly to class components, default props for stateless functional components will work without any extra type annotations.

like image 179
Tomasz Mularczyk Avatar answered Oct 23 '22 07:10

Tomasz Mularczyk