DEV Community

jawwad22
jawwad22

Posted on

Want to implement dark theme in react native app, What will be best approach?

Discussion (3)

Collapse
saraffath profile image
Sarafathulla S • Edited on

idk whether this is the best approach but i think it may help you :

useContext hooks will work in this case. Create a separate colors file and create an 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)
  const value = useMemo(
    () => ({
        colors,
        setColors,
    }),
    [colors, setColors],
  );

  return (
    <ColorThemeContext.Provider value={value}>{children}</ColorThemeContext.Provider>
  );
}

export default ColorThemeProvider;

Inside any component :

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);
}
}
Collapse
induratized profile image
Abhinav Sharma

Stackoverflow

Collapse
dance2die profile image
Sung M. Kim

StackOverflow requires a specific errors one received and requires what one tried, not general questions on directions and tips.

Such a question would fit here better here.