Dark theme in React-Native, React using useContext hook

saraffath

Sarafathulla S

Posted on November 18, 2019

Dark theme in React-Native, React using useContext hook

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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);
}
}
Enter fullscreen mode Exit fullscreen mode

Hope this helps.

Feedbacks and Suggestions are much appreciated.

💖 💪 🙅 🚩
saraffath
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.

Related