Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define prop types using flow for stateless functional components in react native

I am currently using flow and eslint to cleanup our code base.

Eslint tells you to convert stateless components to stateless functional components. But I haven't found an example for how their props get properly typed for flow. Here is what I tried:

original component:

type Props = {onPress : Function}

export default class MyButton extends React.Component <Props> {
  render() {
    ...  // use this.props.onPress
  }
}

Version 1 (how I would expect a function to work): Here flow says Cannot create MyButton element because a callable signature is missing in props [1] but exists in function type [2].

const MyButton = (onPress: Function) => (
  return(
    ...  // use onPress
  )
}

Version 2 (as seen in here): here eslint complains that onPress cant be found. ${onPress} doesn't work either. Flow complains: Missing type annotation for destructuring.

const MyButton = ({onPress: Function}) => (
  return(
    ...  // use onPress (or ${onPress} ??)
  )
}

So how do I solve this?

like image 224
David Schumann Avatar asked Sep 05 '26 02:09

David Schumann


1 Answers

Your version 2 is close, but you can't define the type inside the destructuring; you have to define the whole object type. It would look like this

type Props = {
  onPress: Function
}
const MyButton = ({ onPress }: Props) => (
  return(
    ...
  )
}
like image 132
TLadd Avatar answered Sep 07 '26 17:09

TLadd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!