Skip to content

Commit 4d6428e

Browse files
authored
[material-ui][Snackbar] Skip default behaviour when defaultMuiPrevent… (#45629)
1 parent f92a6a0 commit 4d6428e

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

docs/data/material/components/snackbars/snackbars.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,23 @@ You can use the `TransitionComponent` prop to change the transition of the Snack
6767

6868
## Customization
6969

70+
### Preventing default click away event
71+
72+
If you would like to prevent the default onClickAway behavior, you can set the event's `defaultMuiPrevented` property to `true`:
73+
74+
```jsx
75+
<Snackbar
76+
slotProps={{
77+
clickAwayListener: {
78+
onClickAway: (event) => {
79+
// Prevent's default 'onClickAway' behavior.
80+
event.defaultMuiPrevented = true;
81+
},
82+
},
83+
}}
84+
/>
85+
```
86+
7087
### Use with Alerts
7188

7289
Use an Alert inside a Snackbar for messages that communicate a certain severity.

packages/mui-material/src/Snackbar/Snackbar.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,11 @@ const Snackbar = React.forwardRef(function Snackbar(inProps, ref) {
188188
externalForwardedProps,
189189
getSlotProps: (handlers) => ({
190190
onClickAway: (...params) => {
191+
const event = params[0];
191192
handlers.onClickAway?.(...params);
193+
if (event?.defaultMuiPrevented) {
194+
return;
195+
}
192196
onClickAway(...params);
193197
},
194198
}),

packages/mui-material/src/Snackbar/Snackbar.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -622,4 +622,27 @@ describe('<Snackbar />', () => {
622622
expect(child).toHaveComputedStyle({ transitionDuration: '0.001s, 0.001s' });
623623
});
624624
});
625+
626+
it('should skip default clickAway behavior when defaultMuiPrevented is true', () => {
627+
const handleClose = spy();
628+
render(
629+
<Snackbar
630+
open
631+
onClose={handleClose}
632+
message="message"
633+
slotProps={{
634+
clickAwayListener: {
635+
onClickAway: (event) => {
636+
event.defaultMuiPrevented = true;
637+
},
638+
},
639+
}}
640+
/>,
641+
);
642+
643+
const event = new window.Event('click', { bubbles: true, cancelable: true });
644+
document.body.dispatchEvent(event);
645+
646+
expect(handleClose.callCount).to.equal(0);
647+
});
625648
});

0 commit comments

Comments
 (0)