Is there a way to specify member variable flow type for stateless functional component?
const Login = ({ login, logging, ...props }: Object) => {
return (
<BaseTextInput
inputRef={ref => {
this.emailInput = ref;
}}
/>
)}
property `emailInput`:
Property cannot be assigned on
global object:
Currently using flowType v0.37.0
What is this supposed to be referencing?
@mwalkerwells this refers to Login element, which is a Stateless React Component. Currently I am using react-native.
this refers to "instances" of a class (more specifically objects created by a constructor function) or an object literal. You have neither in your example.
React "elements" are just syntactic sugar for React.createElement function calls. Login is merely a function that returns a function (input => input => output) & there is no object for this to refer to (or context); you need to pass in directly.
Your example is the same as this:
js
const Login = ({ login, logging, ...props }: Object) =>
React.createElement(BaseTextInput, {
inputRef: ref => { this.emailInput = ref }
})
You need to pass the context directly, since this a functional component and there is no state / instance variables to store intermediate data.
js
const Login = ({ context, login, logging, ...props }: Object) =>
React.createElement(BaseTextInput, {
inputRef: ref => { context.emailInput = ref }
})
You'd then use it like this:
````js
class Form extends React.Component {
emailInput: string
render() {
return (
)
}
}
````
One other note: The Object type is merely any scoped to objects. It's better to be more declarative to guarantee type safety.
My example works without passing in context. Fixing the issue by yet again wrapping it with class seems to defeat one of the purposes of using stateless functional component.
Is there way to supress flowType error Property cannot be assigned on global object for a particular file?
Thanks
You have to declare the required context (https://facebook.github.io/react/docs/context.html), but it requires a non-functional component IIRC.
You can't use this in stateless components, so this is an actual error
@vkurchatkin This is a working example
@ericapply It may work, but it's not safe.
@mwalkerwells I disagree, this is perfectly safe.
This example works because this refers to the global object. This will break if you have more than one Login rendered
Makes sense, I thought flow was complaining because I didn't specify the type, but basically I was doing something unsafe. Thanks for the clarification!
Most helpful comment
This example works because
thisrefers to the global object. This will break if you have more than oneLoginrendered