NativeBase provides multiple tools to use the central theme defined in the app. The first tool is
, which you can use to access the values from the current theme.
function ColorPalete() {
const {
colors
} = useTheme();
return <Box>
<FlatList numColumns="5" data={Object.keys(colors["primary"])} renderItem={({
item
}) => <Box p="5" bg={`primary.${item}`} />} />
</Box>;
}
function Example() {
return <NativeBaseProvider>
<Center flex={1} p="3">
<ColorPalete />
</Center>
</NativeBaseProvider>;
}
You can also get specific values from the theme with
hook.
function Tokens() {
const [contrastThreshold, darkText] = useToken("colors", ["contrastThreshold", "darkText"]);
return <Center bg="primary.600" flexDirection="row" p="4" rounded="4">
Contrast threshold is:{" "}
<Text color={darkText} fontWeight="bold">
{contrastThreshold}
</Text>
</Center>;
}
function Example() {
return <NativeBaseProvider>
<Center flex={1}>
<Tokens />
</Center>
</NativeBaseProvider>;
}
If you are defining the background yourself and want to pass a contrasting color to the text, then you can use
.
function UseContrastingTextHook() {
const bgDark = "primary.600";
const bgLight = "primary.200";
const colorContrastDark = useContrastText(bgDark);
const colorContrastLight = useContrastText(bgLight);
return <Stack space="4">
<Button bg={bgDark} _text={{
color: colorContrastDark
}}>
NativeBase
</Button>
<Button bg={bgLight} _text={{
color: colorContrastLight
}}>
NativeBase
</Button>
</Stack>;
}
function Example() {
return <NativeBaseProvider>
<Center flex={1}>
<UseContrastingTextHook />
</Center>
</NativeBaseProvider>;
}
If you want to define some conditionals based on current color mode or change the color mode, then you can try
.
function UseColorMode() {
const {
colorMode,
toggleColorMode
} = useColorMode();
return <Center flex="1" p="4" bg={colorMode === "dark" ? "coolGray.800" : "warmGray.50"}>
<Text fontSize="lg" display="flex" mb="20">
The active color mode is{" "}
<Text bold fontSize="lg">
{colorMode}
</Text>
</Text>
<Button onPress={toggleColorMode}>Toggle</Button>
</Center>;
}
function Example() {
return <NativeBaseProvider>
<Center flex={1}>
<UseColorMode />
</Center>
</NativeBaseProvider>;
}
If you do not want to add conditionals for color mode everywhere and keep the code clean, then you can use
hook. It takes two parameters, light mode value as the first and dark mode value as second.
function UseColorMode() {
const {
toggleColorMode
} = useColorMode();
const backgroundColor = useColorModeValue("warmGray.50", "coolGray.800");
const colorMode = useColorModeValue("Light", "Dark");
return <Center flex={1} p="4" bg={backgroundColor}>
<Text fontSize="lg" display="flex" mb="20">
The active color mode is{" "}
<Text bold fontSize="18px">
{colorMode}
</Text>
</Text>
<Button onPress={toggleColorMode}>Toggle</Button>
</Center>;
}
function Example() {
return <NativeBaseProvider>
<Center flex={1}>
<UseColorMode />
</Center>
</NativeBaseProvider>;
}