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 ponent
import React from "react";
import GlobalStyles from "../globalStyles.js"
class Inventory extends React.Component {
render() {
return (
<View style={globalStyles.container}>
)
}
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 ponent
import React from "react";
import GlobalStyles from "../globalStyles.js"
class Inventory extends React.Component {
render() {
return (
<View style={globalStyles.container}>
)
}
Share
Improve this question
edited Nov 2, 2023 at 20:02
TylerH
21.1k77 gold badges79 silver badges112 bronze badges
asked Dec 11, 2020 at 20:22
JohnJohn
8299 silver badges22 bronze badges
1 Answer
Reset to default 14You have a couple of issues: you can only use a hook within a hook or a function ponent. 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 repute 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 ponent into a function ponent 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}>
)
}