React Native FlatList, Styled Components and Typescript
Asked Answered
C

2

5

I have a historic ongoing battle with styled-components , FlatList and typescript ... Up until now I've been able to make it work with the following :

const StyledList = styled(FlatList as new () => FlatList<ItemType>)<CustomProps>(props => ({
  .......
}));

This worked fine until I did a recent project upgrade and it's broken this approach. I now have the following dependency versions:

"typescript": "~4.3.5"

"styled-components": "^5.3.3"

"react-native": "0.64.3"

The errors are like this :

Property 'data' does not exist on type 'IntrinsicAttributes & { ref?: Ref<FlatList< ItemType >> | undefined; key?: Key | null | undefined; } & { theme?: DefaultTheme | undefined; } & { ...; } & { ...; }'.

Can anyone offer any insight into this please? What might have changed in recent versions of styled-components or react-native to prevent the original workaround from working?

Coworker answered 8/2, 2022 at 14:37 Comment(0)
S
6
import { FlatList, FlatListProps } from 'react-native';
    
const List = styled(FlatList as new (props: FlatListProps<ItemType>) => FlatList<ItemType>)``;

It works for me.

Sloshy answered 1/3, 2022 at 18:56 Comment(3)
I just had to log in to personally thank you! This works like a charm. (react-native: 0.67.3, typescript: 4.4.4, styled-components: 5.3.3).Kernite
Thanks! After hours of research, found your answer... this works like a charm 🎉Dilks
Any way to make item type generic ? example: export type StyledFlatList<T> = FlatList<T>; export const StyledFlatList = styled(FlatList as new <T>(props: FlatListProps<T>) => FlatList<T>) not working as expected..Raze
O
0

It's been a while but I found a way to make it work with custom props as well as retain original behaviour.

type FlatListContainerProps<T> = FlatListProps<T> & {
  $noBorder?: boolean;
};
const ExtendedFlatList = <T,>({ $noBorder, ...props }: FlatListContainerProps<T>) => {
  return <FlatList {...props} />;
};
export const FlatListContainer = styled(ExtendedFlatList)<FlatListContainerProps<any>>`
  border-radius: 20px;
  border-width: ${({ $noBorder }: FlatListContainerProps<any>) => ($noBorder ? 0 : "1px")};
  border-color: #f2f2f2;
  background-color: "green";
` as unknown as typeof ExtendedFlatList;

I hope this is helpful.

Oxley answered 7/12, 2023 at 4:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.