Capturar foco
Capturar foco dentro de um nó DOM.
TrapFocus é um componente que gerencia o foco para seus descendentes. This is useful when implementing overlays such as modal dialogs, which should not allow the focus to escape while open.
When open={true}
the trap is enabled, and pressing Tab or Shift+Tab will rotate focus within the inner focusable elements of the component.
A paleta com funções de estilo.
Exemplo
<button type="button" onClick={() => setOpen(true)}>
Open
</button>
{open && (
<TrapFocus open>
<Box tabIndex={-1} sx={{ mt: 1, p: 1 }}>
<label>
First name: <input type="text" />
</label>
<br />
<button type="button" onClick={() => setOpen(false)}>
Close
</button>
</Box>
</TrapFocus>
)}
Unstyled
As the component does not have any styles, it also comes with the Base package.
import TrapFocus from '@mui/base/Unstable_TrapFocus';
Desabilitar o forçar foco
Clicks within the focus trap behave normally, but clicks outside the focus trap are blocked.
Você pode desativar esse comportamento com a propriedade disableEnforceFocus
.
<button type="button" onClick={() => setOpen(true)}>
Open
</button>
{open && (
<TrapFocus disableEnforceFocus open>
<Box tabIndex={-1} sx={{ mt: 1, p: 1 }}>
<label>
First name: <input type="text" />
</label>
<br />
<button type="button" onClick={() => setOpen(false)}>
Close
</button>
</Box>
</TrapFocus>
)}
Ativação tardia
Por padrão, o componente move o foco para seus descendentes assim que abre: open={true}
.
Você pode desabilitar esse comportamento e deixá-lo de forma tardia com a propriedade disableAutoFocus
. Quando o foco automático é desabilitado, como na demonstração abaixo, o componente só captura o foco quando ele for focado.
<button type="button" onClick={() => setOpen(true)}>
Open
</button>
{open && (
<TrapFocus open disableAutoFocus>
<Box tabIndex={-1} sx={{ mt: 1, p: 1 }}>
<label>
First name: <input type="text" />
</label>
<br />
<button type="button" onClick={() => setOpen(false)}>
Close
</button>
</Box>
</TrapFocus>
)}
Portal
The following demo uses the Portal
component to render a subset of the trap focus children into a new "subtree" outside of the current DOM hierarchy; so that they no longer form part of the focus loop.