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

Choose class dynamically through prop ReactNative+Typescript

$
0
0

So I was trying to make this component have the styles assigned dynamically by having the style chosen from the stylesheet depend on the string passed in through the properties

export type MyComponentProps = {  styleName: string;}const MyComponent = (props: MyComponentProps) => {  const { styleName } = props;  return (<View      style={[        styles['container'],        styles[`view${styleName}`],      ]}><Text        style={[          styles['text'],          styles[`text${styleName}`],        ]}>        Hello World</Text></View>  );}MyComponent.defaultProps = {  styleName: 'Dark',}const styles = StyleSheet.create({  container: {    width: '100%',    alignItems: 'center',  },  viewDark: {    backgroundColor: 'black',  },  viewLight: {    borderColor: 'white',  },  text: {    fontWeight: 'bold',  },  textDark: {    color: 'white',  },  textLight: {    color: 'black',  },}

But this raises the error

Element implicitly has an 'any' type because expression of type '`view${any}`' can't be used to index type '{ container: { width: string; alignItems: "center"; }; viewDark: { backgroundColor: string; }; viewLight: { backgroundColor: string; }; text: { ...; }; textDark: { ...; }; textLight: { ...; }; }'.

I was trying to avoid having any styles themselves come in through the props, I see that's something recommended a lot

Also I know it might hurt your eyes to see styles['container'] instead of styles.container, but I just wanted to make it clear what my goal is as much as possible, so having the ${styleName} be the only difference between the two cases would help that


Viewing all articles
Browse latest Browse all 6287

Trending Articles



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