Skip to content

Commit f9283ba

Browse files
authored
[system][createStyled] Intercept ownerState coming from props and ownerState (#42358)
1 parent 79bad36 commit f9283ba

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

packages/mui-system/src/createStyled/createStyled.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,8 @@ function processStyleArg(callableStyle, { ownerState, ...props }) {
5656
);
5757
}
5858

59+
const mergedState = { ...props, ...ownerState, ownerState };
60+
5961
if (
6062
!!resolvedStylesArg &&
6163
typeof resolvedStylesArg === 'object' &&
@@ -66,7 +68,7 @@ function processStyleArg(callableStyle, { ownerState, ...props }) {
6668
variants.forEach((variant) => {
6769
let isMatch = true;
6870
if (typeof variant.props === 'function') {
69-
isMatch = variant.props({ ownerState, ...props, ...ownerState });
71+
isMatch = variant.props(mergedState);
7072
} else {
7173
Object.keys(variant.props).forEach((key) => {
7274
if (ownerState?.[key] !== variant.props[key] && props[key] !== variant.props[key]) {
@@ -79,9 +81,7 @@ function processStyleArg(callableStyle, { ownerState, ...props }) {
7981
result = [result];
8082
}
8183
result.push(
82-
typeof variant.style === 'function'
83-
? variant.style({ ownerState, ...props, ...ownerState })
84-
: variant.style,
84+
typeof variant.style === 'function' ? variant.style(mergedState) : variant.style,
8585
);
8686
}
8787
});

test/integration/mui-system/createStyled.test.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -729,5 +729,37 @@ describe('createStyled', () => {
729729
expect(getByTestId('outlined')).toHaveComputedStyle({ borderTopColor: 'rgb(0, 0, 255)' });
730730
expect(getByTestId('text')).toHaveComputedStyle({ color: 'rgb(0, 0, 255)' });
731731
});
732+
733+
it('should not consume values from nested ownerState', () => {
734+
const styled = createStyled({ defaultTheme: { colors: { blue: 'rgb(0, 0, 255)' } } });
735+
736+
const Test = styled('div')(({ theme }) => ({
737+
variants: [
738+
{
739+
props: ({ ownerState }) => ownerState.color === 'blue',
740+
style: {
741+
backgroundColor: theme.colors.blue,
742+
},
743+
},
744+
],
745+
}));
746+
747+
const ownerState = { color: 'blue' };
748+
749+
const { getByTestId } = render(
750+
<React.Fragment>
751+
<Test data-testid="blue" ownerState={ownerState}>
752+
Blue
753+
</Test>
754+
<Test data-testid="nested" ownerState={{ ownerState }}>
755+
Nested ownerState
756+
</Test>
757+
</React.Fragment>,
758+
);
759+
expect(getByTestId('blue')).toHaveComputedStyle({ backgroundColor: 'rgb(0, 0, 255)' });
760+
expect(getByTestId('nested')).not.toHaveComputedStyle({
761+
backgroundColor: 'rgb(0, 0, 255)',
762+
});
763+
});
732764
});
733765
});

0 commit comments

Comments
 (0)