ABOUT ME

-

  • [ React Native ] 다크모드 테마설정 간단하게 처리하기
    Application/React Native 2025. 10. 6. 21:23
    반응형

    앱을 만들면서 항상 테마 설정을 하는데 react native의 테마 설정하는 방법을 찾아보는데 대부분이 hook을 이용해서 구현하는 방법들이 대부분 이었다.

     

    근데 이러면 내가 원하는 곳에 원하는 색을 넣을려면 해당 컴포넌트에서 결국 hook을 사용해야하기때문에

    컴포넌트에서 계속 hook을 불러와서 쓰는 불편함을 없애고 싶어서 다른 방법으로 구현해보았다.

     


    Initialized

    우선 hook을 사용하지 않고 할려고 해도 상태관리는 해야하기때문에 zustand를 이용

    npm install zustand

    Zustand

    zustand에서 theme 값과 변경 함수를 정의

     

    theme의 타입은 아래처럼 select에서 선택해서 설정할 수 있게 할 것이므로 해당 key값을 가져와서 타입 정의

    export const selectTheme:SelectOption = {
        'white': '화이트 테마',
        'dark': '다크 테마'
    }
    import {create} from "zustand/react";
    import {selectTheme} from "@/constant/setting.ts";
    
    interface AppState {
        theme: keyof typeof selectTheme
        setTheme: (val: keyof typeof selectTheme) => void
    }
    
    export const useAppStore = create<AppState>((set,get) => ({
        theme: 'white',
        setTheme: (val) => set({theme: val})
    }))

     


    Theme Typescript

    이후 각 테마별 색상을 관리할 타입스크립트 파일을 생성

    이때 theme변수는 let으로 선언하여 테마가 바뀔때마다 해당 theme의 값으로 바꿀 수 있도록 처리

     

    setTheme함수는 let으로 선언한 theme변수를 바꿀 함수 이것은 store의 setTheme과는 별개이다.

    import {selectTheme} from "@/constant/setting.ts";
    
    export interface Theme {
        app_theme_background: string,
        app_theme_boxBackground: string,
        app_theme_textcolor: string
    }
    
    const WHITE_THEME: Theme = {
        app_theme_background: '#ffffff',
        app_theme_boxBackground: '#ffffff',
        app_theme_textcolor: '#000000'
    }
    
    const DARK_THEME: Theme = {
        app_theme_background: '#000000',
        app_theme_boxBackground: '#333333',
        app_theme_textcolor: '#ffffff'
    }
    
    export const colortheme: Record<keyof typeof selectTheme, Theme> = {
        'white': WHITE_THEME,
        'dark': DARK_THEME,
    }
    
    export let theme = colortheme['white']
    
    export const setTheme = (value:  keyof typeof selectTheme) => {
        theme = colortheme[value]
    }

    Useage

    사용할때는 우선 store에서는 현재 테마를 가져온다.

    이후 테마가 변경되면 store에서도 한번 바꿔주고,

    이후 theme typescript에서 만든 setTheme함수를 활용해 let 변수를 바꿔준다.

    const appStore = useAppStore()
        /* theme */
        const [appTheme, setAppTheme] = useState<keyof typeof selectTheme>(appStore.theme);
    
        const onSelectTheme = (value: keyof typeof selectTheme) => {
            setAppTheme(value)
            appStore.setTheme(value)
        }

     

    이후 사용할때에는 theme.색상코드변수key값으로 색상을 설정해준다.

    <View style={[styles.container, {
                    backgroundColor: theme.app_theme_background
                }]}>

     

    그러면 테마가 바뀔때마다 theme값이 바뀌면서 테마 변경이 가능하다

    이후 테마가 변경할 때마다 local storage에 저장을 해주면 된다.

     

    이러면 테마 색 변경이 필요한 곳마다 hook선언을 하지 않고 단순히 theme변수만 사용하면 테마 변경이 가능하다.

    728x90
    반응형