DEV Community

jawwad22
jawwad22

Posted on

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

Top comments (3)

Collapse
 
saraffath profile image
Sarafathulla S • Edited

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);
}
}

Some comments may only be visible to logged-in visitors. Sign in to view all comments.