Skip to content

Instantly share code, notes, and snippets.

@kubilaykiymaci
Last active September 30, 2023 06:13
Show Gist options
  • Save kubilaykiymaci/fe928f338e5c10adb2de6c8885c1e0fb to your computer and use it in GitHub Desktop.
Save kubilaykiymaci/fe928f338e5c10adb2de6c8885c1e0fb to your computer and use it in GitHub Desktop.
React - Flow Example
// @flow : which files we want to flow will monitor
import * as React from 'react' // let’s flowify the component we just wrote
import Xcomponent from "xcomponent"
const GridType = {
article: "article",
text: "text",
test: "test"
}
type PropsType = {
name?: ?string, // first ? means: this props is optional
// second ? means: this type can be Null
size?: Object | null, // size is optional prop and it can be Object or Null
onChange: () => void, // onChange prop is a function and its required because it hasn't ?
currencyList?: Array<string>, // currencyList is a Array which elements type string
grid: $Values<typeof GridType>, // usage of OneOf type, grid can be "article", "text", "test"
...$Shape<any> // spread notations
}
type StateType = {
name: string
}
type ContextType = {
context?: Object
}
class Example extends React.Component<PropsType, StateType> {
// To type default props add a static defaultProps property to your class
static defaultProps = {
name: "default name"
}
constructor(props: PropsType, context: ContextType) {
super(props)
this.state.name = "test name"
}
//To use a ref function add a maybe instance type to your class and
// assign your instance to that property in your ref function.
// The `?` here is important because you may not always have the instance.
form: ?React.Component<typeof Form>
handleSubmit(e?: SyntheticEvent<>, values?: any) {
}
//If you need a return type for your component render() methods
//then you should use React.Node. However, if you need a generic type for a children prop,
//use ?React.Node; children can be undefined, when render() can’t return undefined
render(): React.Node {
return(
<Form
ref={(c: ?React.Component<typeof Form>) => {
this.form = c
}}
...
)
}
}
Example.contextTypes = {} // React.Component created with Props and StateType,
// So you should define contextType for external Context access
export default Example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment