Bastian
Bastian

Reputation: 4738

React Native SectionList has incomprehensible flow type error

If have this simple SectionList definition in my code:

const s = (
  <SectionList
    renderItem={({ item }) => <Text>abc</Text>}
    renderSectionHeader={({ section }) => <Text>abc</Text>}
    sections={[{ data: [1, 2, 3], title: 'abc' }]}
  />
);

And flow generates this error message which refers to the whole "tag block" (it is actually copy pasted from VSCode):

[flow] props of React element `SectionList` (This type is incompatible with See also: React element `SectionList`)

What is happening here?

EDIT I am using

flow-bin: 0.56.0
react: 16.0.0
react-native: 0.49.1

EDIT2 So the example can be reduced to this simple line (without impacting the error message):

<SectionList sections={[]} />;

EDIT3 I just discovered that flow complains about several types that are defined in the React Native library (mainly about missing type arguments for generic types). I am wondering if I should use an older flow-bin version. Is there a compatibility table for React Native and flow?

Upvotes: 5

Views: 1671

Answers (4)

Phaoga54
Phaoga54

Reputation: 51

interface SectionDataModel {
...
}

const [sections, setSections] = useState<ReadonlyArray<SectionDataModel> | []>([]) This worked for me

Upvotes: 0

phatmann
phatmann

Reputation: 18493

The OP's code should have gotten no complaints from Flow as it is valid.

I had a related issue in that I was using a state that held sections and I could not find the right type for Flow. I could not use SectionBase directly since it did not have the extra title property I needed. I solved it by using an intersection type:

type Section = { title: string } & SectionBase<ScheduleChange>
type State { sections: Section[] }

...

<SectionList
    sections = this.state.sections
    ...
/>

Upvotes: 1

Johannes
Johannes

Reputation: 1440

React has a built in Flow type for sections called SectionBase:

import type { SectionBase } from 'react-native/Libraries/Lists/SectionList'
type Section = SectionBase<DataType>

So based on what Martin answered you would write: SectionBase<Row>

Upvotes: 4

Martin
Martin

Reputation: 171

I had a similar problem with react-native: 0.49.3 and flow-bin: 0.53.0. After checking the type definitions from the SectionList source, got it to work without type warnings as follows:

type Row = {
  name: string,
}

type Section = {
  title: string,
  data: $ReadOnlyArray<Row>,
}

const mySections: $ReadOnlyArray<Section> = [...] // your data here

<SectionList sections={mySections} />

So the key for me was to use $ReadOnlyArray<T> instead of Array<T>. Perhaps this helps you!

Upvotes: 5

Related Questions