Flow (React Native) is giving me errors for using 'this.state'

You need to define a type for the state property in order to use it.

class ComponentA extends Component {
    state: {
        isExpanded: Boolean
    };
    constructor(props) {
        super(props);
        this.state = {
            isExpanded: false
        };
    }
}

If you're using flow and want to set this.state in your component's constructor:


1. Create a type for this.state

type State = { width: number, height: number }

2. Initialize your component with that type

export default class MyComponent extends Component<Props, State> { ... }

3. Now you can set this.state without any flow errors

  constructor(props: any) {
    super(props)
    this.state = { width: 0, height: 0 }
  }

Here's a more complete example that updates this.state with the width and height of the component when onLayout is called.

// @flow

import React, {Component} from 'react'
import {View} from 'react-native'

type Props = {
  someNumber: number,
  someBool: boolean,
  someFxn: () => any,
}

type State = {
  width: number,
  height: number,
}

export default class MyComponent extends Component<Props, State> {

  constructor(props: any) {
    super(props)

    this.state = {
      width: 0,
      height: 0,
    }
  }

  render() {

    const onLayout = (event) => {
      const {x, y, width, height} = event.nativeEvent.layout
      this.setState({
        ...this.state,
        width: width,
        width: height,
      })
    }

    return (
      <View style={styles.container} onLayout={onLayout}>

        ...

      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center',
  },
})