React & Typescript: nested defaultProps deep merge

Viewed 454

I'm creating a React & Typescript component and need to define some default props which are objects with nested data. Here is a simplified example of my component:

type Props = {
    someProp: string,
    user: {
        blocked: boolean,
        active: boolean
    }
}

export const UserPage: React.FC<Props> = props => {
    (...)
};

Then I define default props like so:

const defaultProps: Props = { 
    user: {
        blocked: true
    }
}

UserPage.defaultProps = defaultProps

The problem is, if my component is called with the following props

<UserPage user={{ active: true }}/>

than the user object in the default props will be overwritten completely.

What is the best way to declare and merge props and default props with nested data?

1 Answers

You can use

const propsWithDefaults = Object.assign(defaultProps, props);
Related