Dark theme in React-Native, React using useContext hook
Sarafathulla S
Posted on November 18, 2019
Create a separate file and construct object like this
const mainColors = {
lightTheme: {
//light theme colors
type : 'light',
fontColor: 'black'
},
darkTheme: {
//dark theme colors
type : 'dark',
fontColor: 'white'
}
//common colors
}
export default mainColors;
Theme Provider Context :
import React, { createContext, useState, useMemo } from 'react';
import mainColors from '../theme/mainColors';
export const ColorThemeContext = createContext();
function ColorThemeProvider({ children }) {
const [colors, setColors] = useState(mainColors.lightTheme) //setting light theme as default
const value = useMemo(
() => ({
colors,
setColors,
}),
[colors, setColors],
);
return (
<ColorThemeContext.Provider value={value}>{children}</ColorThemeContext.Provider>
);
}
export default ColorThemeProvider;
Inside any component that has ColorThemeProvider as its wrapper :
const {colors, setColors} = useContext(ColorThemeContext); //assume currently lightTheme is applied
...
<Text style={{color : colors.fontColor}} > text </Text>
Changing dark theme :
const {colors, setColors} = useContext(ColorThemeContext); //assume currently lightTheme is applied
....
function onAction() {
if(colors.type === 'light') {
setColors(mainColors.darkTheme);
} else {
setColors(mainColors.lightTheme);
}
}
Hope this helps.
Feedbacks and Suggestions are much appreciated.
💖 💪 🙅 🚩
Sarafathulla S
Posted on November 18, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.