How to use an enum in typescript as a default prop value for a react component

Viewed 912

I have an enum file Themes.ts

export enum Themes {
    DEFAULT = 'default',
    DARK = 'dark'
}

And I want to use that enum as a default prop in a <Test/> component that looks like

export type TestProps = {
    children: ReactChild,
    theme?: Themes,
}

export const Test = ({ children, theme = Themes.DEFAULT }: TestProps) => {
    console.log(theme)
    return (
        <div className={`${theme}`}>
            <div>
                { children }
            </div>
        </div>
    )
}

The issue i'm seeing is that console.log(theme) is printing Themes.DEFAULT instead of default so the default value isn't being set properly. Is there anyway to use an enum to set this default theme value so that it will evaluate properly?

EDIT : What ended up working was setting a const to the enum values and then passing that into the props

const enumValue = Themes.DEFAULT
export const Test = ({ children, theme = enumValue }: TestProps) => {
2 Answers

Use string union types instead of enums. This way you keep the same type strength and your strings can be strings.

export type Themes = 'default' | 'dark';

Then in your component

export type TestProps = {
    children: ReactChild,
    theme?: Themes,
}

export const Test = ({ children, theme = 'default' }: TestProps) => {
    console.log(theme)
    return (
        <div className={`${theme}`}>
            <div>
                { children }
            </div>
        </div>
    )
}

If you try to assign anything besides 'default' or 'dark', the TS compiler will throw an error.

Related