Reputation: 41
I use nativewind(tailwind) in rect-native. I'm working on dark/light mode. I want to do it in the nicest possible way, clean code.
I want <Text className='text-white dark:text-black'>
to be for example<Text className='text-textColor'>
instead of this.
tailwind.config.js
module.exports = {
content: ['./App.{js,jsx,ts,tsx}', './src/**/*.{js,jsx,ts,tsx}'],
theme: {
extend: {
colors: {
'primary': '#fffff',
},
},
},
plugins: [],
};
I have one possible solution that works but it is not the best possible solution.
const { colorScheme, toggleColorScheme } = useColorScheme();
const colors = {
text: colorScheme === 'dark' ? 'white' : 'black',
};
<Text className={`text-${colors.text}`}>
Upvotes: 3
Views: 4109
Reputation: 431
Firstly, you need to know that tailwind do not accept interpolation on class names. For example:
<Text className={`text-${colors.text}`}>
Here is how you can fix that.
Now, answering the question, according to the documentation you can use the dark:
variant and it will be controlled by useColorScheme()
.
If you're using
expo
, you need to modify yourapp.json
changing theuserInterfaceStyle
to automatic:app.json
{ "expo": { "userInterfaceStyle": "automatic" } }
To manipulate theme's state, you could use a simple useState/Context API
(not persisted) or AsyncStorage/MMKV/...
(persisted state). After that, you can use dark:
variant in that way:
import { Pressable, Text } from "react-native"
import { useColorScheme } from "nativewind";
function App() {
const { colorScheme, toggleColorScheme } = useColorScheme();
return (
<Pressable
className="flex-1 items-center justify-center bg-neutral-100 dark:bg-neutral-900"
onPress={toggleColorScheme}>
<Text className="text-black dark:text-white">
{`Try clicking me! ${colorScheme === "dark" ? "🌙" : "🌞"}`}
</Text>
</Pressable>
);
}
The base of this example was extracted from the documentation
I hope to help you.
Upvotes: 3
Reputation: 607
just try this
const { colorScheme, toggleColorScheme } = useColorScheme();
const colors = {
text: colorScheme === 'dark' ? 'text-white' : 'dark:text-black',
};
<Text className={colors.text}>
Upvotes: -2