const MyComponent = (props: {value: number}) => {
<div>{props.value}</div>
};
MyComponent.defaultProps = {
value: 10
};
<MyComponent />;
Gives errors:
7: const MyComponent = (props: {value: number}) => {
^ property `value`. Property not found in
15: <MyComponent />;
^ props of React element `MyComponent`
How to use defaultProps with functional components? Class based works fine:
class MyComponent extends React.Component {
static defaultProps = { value: 10 }
render() {
return <div>{this.props.value}</div>;
}
}
const MyComponent = ({value = 10}: {value: number}) =>
this should work I think ^
It's true that Flow doesn't understand the pattern of adding defaultProps
to the statics of the function object. In general, it's fairly tricky to do that and destructuring+defaults works well already so we haven't invested time to make the statics pattern work.
If destructuring in the params list is too cumbersome, remember that you can also provide defaults in the body:
export function f(props: { foo?: number }) {
var {foo = 0} = props;
return <p>thrice {foo} is {3*foo}</p>;
}
destructuring+defaults can get messy (non-DRY) in some cases where it makes more sense to just have a reference to props. @samwgoldman thanks using the function body as a workaround makes sense!
Just for my understanding, how is it harder to do (compared to React.Component defaults) knowing that <Component>
calls React.createElement and therefore always pass props with defaults from the static defaultProps? Is this something the react team could implement in their flow defs?
Most helpful comment
destructuring+defaults can get messy (non-DRY) in some cases where it makes more sense to just have a reference to props. @samwgoldman thanks using the function body as a workaround makes sense!
Just for my understanding, how is it harder to do (compared to React.Component defaults) knowing that
<Component>
calls React.createElement and therefore always pass props with defaults from the static defaultProps? Is this something the react team could implement in their flow defs?