Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native navigation useTheme()

I'm trying to access useTheme() directly from the styles But so far my solution doesn't seem to work. I'm not getting in error back. Is there a way to do what I'm trying to do?

 import { StyleSheet } from "react-native";

    import { useTheme } from '@react-navigation/native'
    
    export default function () {
            const { colors } = useTheme();
            const styles = GlobalStyles({ colors: colors })
            return styles
        }
        
        const GlobalStyles = (props) => StyleSheet.create({
        
            container: {
                flex: 1,
                backgroundColor: props.colors.backgroundColor,
        
            },
        })

Accessing style in component

 import React from "react";
import GlobalStyles from "../globalStyles.js"
    
    class Inventory extends React.Component {
    
    render() {
    
            return (
                <View style={globalStyles.container}>
            )
    
     }
like image 669
John Avatar asked Jul 18 '26 19:07

John


1 Answers

You have a couple of issues: you can only use a hook within a hook or a function component. So you could convert your global stylesheet into a hook:

import { StyleSheet } from "react-native";
import { useTheme } from '@react-navigation/native'
    
const getGlobalStyles = (props) => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: props.colors.backgroundColor,
  },
});

function useGlobalStyles() {
  const { colors } = useTheme();

  // We only want to recompute the stylesheet on changes in color.
  const styles = React.useMemo(() => getGlobalStyles({ colors }), [colors]);

  return styles;
}

export default useGlobalStyles;

Then you can use the hook by converting your Inventory class component into a function component and using the new useGlobalStyles hook.

import React from "react";
import useGlobalStyles from "../globalStyles.js"
    
const Inventory = () => {
  const globalStyles = useGlobalStyles();

  return (
    <View style={globalStyles.container}>
  )
}
like image 157
ljbc1994 Avatar answered Jul 21 '26 08:07

ljbc1994



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!