I'm building a React Native app using TypeScript. I'm trying to use a SectionList
. I followed the docs, and here is my code:
renderSectionHeader = ({ section: { title } }: { section: { title: string } }) => (
<ListItem title={title} />
);
render() {
const { sections } = this.props;
return (
<SafeAreaView style={styles.container}>
<SectionList
keyExtractor={this.keyExtractor}
sections={[
{title: 'Title1', data: ['item1', 'item2']},
{title: 'Title2', data: ['item3', 'item4']},
{title: 'Title3', data: ['item5', 'item6']},
]}
renderItem={this.renderItem}
renderSectionHeader={this.renderSectionHeader}
/>
</SafeAreaView>
);
}
But the line renderSectionHeader={this.renderSectionHeader}
throws the following TSLint Error:
[ts]
Type '({ section: { title } }: { section: { title: string; }; }) => Element' is not assignable to type '(info: { section: SectionListData<any>; }) => ReactElement<any> | null'.
Types of parameters '__0' and 'info' are incompatible.
Type '{ section: SectionListData<any>; }' is not assignable to type '{ section: { title: string; }; }'.
Types of property 'section' are incompatible.
Type 'SectionListData<any>' is not assignable to type '{ title: string; }'.
Property 'title' is missing in type 'SectionListData<any>'. [2322]
Are the types of SectionList
broken? Or is the example wrong? Or am I doing something wrong?
SectionList s are like FlatList s, but they can have section headers to separate groups of rows. SectionList s render each item in their input sections using the renderSectionHeader and renderItem prop. Each item in sections should be an object with a unique id (the key), and an array data of row data.
While React Native is built in Flow, it supports both TypeScript and Flow by default.
interface Data {
...
}
const MySectionList = SectionList as SectionList<Data>;
<MySectionList
...
/>
worked for me
[
{ title: "Title1", data: ["item1", "item2"] },
{ title: "Title2", data: ["item3", "item4"] },
{ title: "Title3", data: ["item5", "item6"] },
]
first you need to define the Section Type
& the date item Type
.
I'll use an interface here to define them.
type Item = string
interface Section {
title: string;
data: Item[]
}
now you need to define your `SectionList` `renderItem` function
const renderItem: SectionListRenderItem<Item, Section> = ({ item }) => {
// make sure you return some sort of a component here.
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With