javascriptreactjsmaterial-uimui-x-data-grid

Material-UI, merging slots from props to Child Component


I have a lot of datagrid components that are very similiar to each other minus some params that I pass as props, they share the same Custom Footer inside of the slots and some styling

export default function CustomizedDataGrid(otherParams) {
return (
            <Box sx={{ width: "100%", overflow: "hidden" }}>
                <DataGrid
                    disableRowSelectionOnClick
                    sx={{
                        border: "none",
                        overflowY: "hidden",
                        width: "100%",
                    }}
                    slots={{
                        footer: CustomFooter
                    }}
                    {...otherParams}
                    />
            </Box>
        ); }

But when I instance CustomizedDataGrid, and pass a slot params like so

export default function SpecializedDataGrid() {
return (
      <CustomizedDataGrid
            columns={columns}
            rows={rows}
            slots={{
                toolbar: CustomToolbar,
            }} /> ); }

It overrides the slots declared inside of CustomizedDataGrid, so that the toolbar shows up, but not the footer. Is there a way to merge the params I passed as props inside of SpecializedDataGrid to the ones I declared inside of CustomizedDataGrid?


Solution

  • Updated CustomizedDataGrid component with slot merging:

    export default function CustomizedDataGrid({ slots: customSlots = {}, ...otherParams }) {
        return (
            <Box sx={{ width: "100%", overflow: "hidden" }}>
                <DataGrid
                    disableRowSelectionOnClick
                    sx={{
                        border: "none",
                        overflowY: "hidden",
                        width: "100%",
                    }}
                    slots={{
                        footer: CustomFooter, // default slot
                        ...customSlots,      // override or add more slots
                    }}
                    {...otherParams}
                />
            </Box>
        );
    }
    

    Usage in SpecializedDataGrid stays the same:

    export default function SpecializedDataGrid() {
        return (
            <CustomizedDataGrid
                columns={columns}
                rows={rows}
                slots={{
                    toolbar: CustomToolbar,
                }}
            />
        );
    }