15

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?

laneherby
  • 405
  • 5
  • 15

2 Answers2

24

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>
  );
}
maphongba008
  • 2,114
  • 4
  • 20
  • 33
1

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.

Rajitha
  • 47
  • 5