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

How to pass props to StyleSheet on custom view in React Native?

$
0
0

So, I have a custom view. On that view, besides taking the children components, I also wanna take backgroundColor and some other StyleSheet property so I can style it depends on the screens.

This is the App.tsx.

export const MainScreen = ({}: Props) => {  return (<CustomView backgroundColor={"#000"}><Text>Example</Text></CustomView>  );};

And this is the CustomView.tsx

type Props = {  children: React.ReactNode;  backgroundColor: string;};export const CustomView = ({ children, backgroundColor }: Props) => {  return <View style={styles.container}>{children}</View>;};const styles = StyleSheet.create({  container: {    flex: 1,    justifyContent: "center",    alignItems: "center",  },});

Say, I wanna change the background color for this screen to #000 like on the codes above. But, I don't know how to handle the props on the CustomView so it can change the backgroundColor.

I tried writing this code

return <View style={styles.container, {backgroundColor: backgroundColor}}>{children}</View>;

But it overwrites the styles.container. On the other hand, if I write this

return <View style={{backgroundColor: backgroundColor}, styles.container}>{children}</View>;

It always throws the error that the left side of comma (the backgroundColor itself) is unused and has no side effects.

So, what should I do? How can I pass the props to handle the StyleSheet?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



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