DEV Community

Sarafathulla S
Sarafathulla S

Posted on

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.

Top comments (1)

Collapse
 
soroushm profile image
Soroush

there is lib Ready to go
npmjs.com/package/@material-native...

Good Luck