reactjstypescriptmobxmobx-react

Pass both props and observer to observed component


How can I pass both props and a store to a Mobx observer component? Here is the observed component. I don't get any errors when I try to access props.isFilterDrawerOpen in the component

export interface Props {
    isFilterDrawerOpen: boolean
}

export const Dashboard = observer(({myStore, props} : {myStore: MyStore, props: PropsWithChildren<Props>}) => {
//...
});

However, when I try to use Dashboard as below:

            <Dashboard
              myStore={myStore}
              isFilterDrawerOpen={isFilterDrawerOpen} />

I get this error:

TS2322: Type '{ myStore: MyStore; isFilterDrawerOpen: boolean; }' is not assignable to type 'IntrinsicAttributes &amp; { myStore: MyStore; props: PropsWithChildren&lt;Props&gt;; }'.
Property 'isFilterDrawerOpen' does not exist on type 'IntrinsicAttributes &amp; { myStore: MyStore; props: PropsWithChildren&lt;Props&gt;; }'.

I can pass props parameter manually like this, but I'd be nice if I can achieve the above.

            <Dashboard
              myStore={myStore}
              props={{isFilterDrawerOpen: isFilterDrawerOpen}} />

Solution

  • You have defined your observer component props to have 2 props "fields": myStore and props, where props is an object of type Props with a isFilterDrawerOpen field, that's why you have to pass them as props={{isFilterDrawerOpen: isFilterDrawerOpen}} to not get errors. You can think of it as usual object fields, since it really is just a parameter object in your arrow function, so there's 2 fields so far.
    Instead you can define it as:

    export interface Props {
        myStore: YourStoreType
        isFilterDrawerOpen: boolean
    }
    
    export const Dashboard = observer(({myStore, isFilterDrawerOpen}: Props) =>{})
    

    You can define as many props as you want and type them accordingly. You can check more examples in Mobx React docs.
    You can check a sandbox here as well, where you can see observer component being created with custom Props.