FocusTrap
Keeps keyboard focus within its children while active. On activation it moves focus inside, cycles Tab / Shift+Tab at the boundaries, pulls focus back when it escapes, and restores focus to the previously focused element on deactivation. Used by Modal to make overlays keyboard-accessible.
Renders a focus-scope wrapper <div tabIndex={-1}> around its children; when there are no focusable descendants, the wrapper itself receives focus.
Examples
Default
Focus trap
Tab and Shift+Tab cycle through these fields without leaving the panel.
const args: Partial<FocusTrapProps> = {
isEnabled: true,
shouldAutoFocus: true,
shouldTrapFocus: true,
shouldEnforceFocus: true,
shouldRestoreFocus: true,
}
<Flex flexDirection="column" gap={3} alignItems="flex-start">
{/* Outside the trap: try to Tab or click here - with shouldEnforceFocus on,
focus is pulled straight back inside the panel. */}
<TextInput inputProps={{ placeholder: 'Outside the trap' }} />
<FocusTrap {...args}>
<Paper p={4} width="320px">
<Flex flexDirection="column" gap={3}>
<Typography variant="h5" m={0}>
Focus trap
</Typography>
<Typography variant="body2" color="secondary" m={0}>
Tab and Shift+Tab cycle through these fields without leaving the panel.
</Typography>
<TextInput fullWidth inputProps={{ placeholder: 'First name' }} />
<TextInput fullWidth inputProps={{ placeholder: 'Last name' }} />
<TextInput fullWidth inputProps={{ type: 'email', placeholder: 'Email' }} />
<Button>Submit</Button>
</Flex>
</Paper>
</FocusTrap>
</Flex>