laneherby
laneherby

Reputation: 485

How do I use the useTheme hook inside my Stylesheet create?

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

Answers (3)

SurabayanFreak77
SurabayanFreak77

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

Rajitha
Rajitha

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

maphongba008
maphongba008

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

Related Questions