Reputation: 485
I want to use the colors from my react native paper theme inside the stylesheet create function inside my component. Here's my code
import { StyleSheet, Text, View } from 'react-native';
import { useTheme } from 'react-native-paper';
const Home = () => {
const { colors } = useTheme();
return (
<View style={[styles.container, { backgroundColor: colors.background }]}>
<Text>Home Page</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default Home;
I want to have the backgroundColor: "#fff" in the stylesheet to reference the colors.background coming from the useTheme hook. Is this possible?
Upvotes: 22
Views: 14523
Reputation: 31
import {Theme, useTheme} from '@react-navigation/native';
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
function HomeScreen(): React.JSX.Element {
const theme = useTheme();
const styles = makeStyles(theme);
return (
<View style={styles.container}>
<Text>Home</Text>
</View>
);
}
const makeStyles = ({colors}: Theme) =>
StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
alignItems: 'center',
justifyContent: 'center',
},
});
export default HomeScreen;
this should work for tsx
Upvotes: 3
Reputation: 47
https://stackoverflow.com/a/65259425/8142053
I found this answer very recently from StackOverflow, according to that you can write a customHook and use it inside the custom hook. Please view his answer for a clear understanding.
Upvotes: 1
Reputation: 2353
I prefer to use it like this
const makeStyles = (colors: any) => StyleSheet.create({
container: {
backgroundColor: colors.red,
}
})
then, in render()
const Home = () => {
const { colors } = useTheme();
const styles = makeStyles(colors)
return (
<View style={[styles.container, { backgroundColor: colors.background }]}>
<Text>Home Page</Text>
</View>
);
}
Upvotes: 31