Skip to content

Commit

Permalink
[Grid] Fix columns of nested container (#31340)
Browse files Browse the repository at this point in the history
Co-authored-by: Michał Dudak <[email protected]>
  • Loading branch information
boutahlilsoufiane and michaldudak committed Mar 10, 2022
1 parent c536e23 commit 82b6570
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 18 deletions.
30 changes: 12 additions & 18 deletions packages/mui-material/src/Grid/Grid.js
Original file line number Diff line number Diff line change
Expand Up @@ -312,9 +312,8 @@ const Grid = React.forwardRef(function Grid(inProps, ref) {

const columnsContext = React.useContext(GridContext);

// setting prop before context to accomodate nesting
// colums set with default breakpoint unit of 12
const columns = columnsProp || columnsContext || 12;
// columns set with default breakpoint unit of 12
const columns = container ? columnsProp || 12 : columnsContext;

const ownerState = {
...props,
Expand All @@ -335,21 +334,16 @@ const Grid = React.forwardRef(function Grid(inProps, ref) {

const classes = useUtilityClasses(ownerState);

const wrapChild = (element) =>
columns !== 12 ? (
<GridContext.Provider value={columns}>{element}</GridContext.Provider>
) : (
element
);

return wrapChild(
<GridRoot
ownerState={ownerState}
className={clsx(classes.root, className)}
as={component}
ref={ref}
{...other}
/>,
return (
<GridContext.Provider value={columns}>
<GridRoot
ownerState={ownerState}
className={clsx(classes.root, className)}
as={component}
ref={ref}
{...other}
/>
</GridContext.Provider>
);
});

Expand Down
30 changes: 30 additions & 0 deletions packages/mui-material/src/Grid/Grid.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,36 @@ describe('<Grid />', () => {
// otherwise, max-width would be 50% in this test
expect(container.firstChild).toHaveComputedStyle({ maxWidth: '100%' });
});

it('should apply the correct number of columns for nested containers with undefined prop columns', () => {
const { getByTestId } = render(
<Grid container columns={16}>
<Grid item xs={8}>
<Grid container data-testid="nested-container-in-item">
<Grid item xs={12} />
</Grid>
</Grid>
</Grid>,
);

const container = getByTestId('nested-container-in-item');
expect(container.firstChild).toHaveComputedStyle({ maxWidth: '100%' });
});

it('should apply the correct number of columns for nested containers with columns=12 (default)', () => {
const { getByTestId } = render(
<Grid container columns={16}>
<Grid item xs={8}>
<Grid container columns={12} data-testid="nested-container-in-item">
<Grid item xs={12} />
</Grid>
</Grid>
</Grid>,
);

const container = getByTestId('nested-container-in-item');
expect(container.firstChild).toHaveComputedStyle({ maxWidth: '100%' });
});
});

describe('prop: item', () => {
Expand Down

0 comments on commit 82b6570

Please sign in to comment.