Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6290

How can I pass a dynamic string as a key to a style in TS react-native?

$
0
0

I want to pass the number of rows (a react native style) dynamically. I tried using 'keyof' as some here have suggested in a different issue, but it didn't work. The code itself works, I'd just like TS to stop screaming at me:

Type '{ backgroundColor: string; flex: number; } | { paddingTop: number | undefined; } | { marginTop: number; fontWeight: "800"; fontSize: number; textAlign: "center"; marginBottom: number; } | { ...; } | ... 7 more ... | { ...; }' is not assignable to type 'StyleProp<ViewStyle>'.

Here's the component:

const Col: React.FC<  PropsWithChildren<{    numRows: number;  }>> = ({ children, numRows }) => {  return (<View style={styles[`${numRows}col` as keyof typeof styles]}>{children}</View>  )}

JSX example:

<Row><Col numRows={1}><Text>Prompt</Text></Col><Col numRows={3}><Text>This is the prompt</Text></Col></Row>

Here's the relevant style excerpt:

const styles = StyleSheet.create({//... other styles"1col": {    backgroundColor: "lightblue",    borderColor: "#fff",    borderWidth: 1,    flex: 1  },"2col": {    backgroundColor: "green",    borderColor: "#fff",    borderWidth: 1,    flex: 2  },"3col": {    backgroundColor: "orange",    borderColor: "#fff",    borderWidth: 1,    flex: 3  },"4col": {    backgroundColor: "orange",    borderColor: "#fff",    borderWidth: 1,    flex: 4  }

});


Viewing all articles
Browse latest Browse all 6290

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>