Blazorise FocusTrap component

Manages focus of the forms and its input elements.

TrapFocus is a component that manages focus for its descendants. This is useful when implementing overlays such as modal dialogs, which should not allow the focus to escape while open.

When Active="true" the trap is enabled, and pressing Tab or Shift+Tab will rotate focus within the inner focusable elements of the component.

Examples

By default, the component moves the focus to its descendants as soon as it activated.
<Card>
    <CardBody>
        <Switch TValue="bool" @bind-Value="@focusTrapActive">Active</Switch>
    </CardBody>
    <CardBody>
        <FocusTrap Active="@focusTrapActive">
            <Field Horizontal>
                <FieldLabel ColumnSize="ColumnSize.IsFull.OnTablet.Is2.OnDesktop">First Name</FieldLabel>
                <FieldBody ColumnSize="ColumnSize.IsFull.OnTablet.Is10.OnDesktop">
                    <TextInput Autofocus />
                </FieldBody>
            </Field>
            <Field Horizontal>
                <FieldLabel ColumnSize="ColumnSize.IsFull.OnTablet.Is2.OnDesktop">Last Name</FieldLabel>
                <FieldBody ColumnSize="ColumnSize.IsFull.OnTablet.Is10.OnDesktop">
                    <TextInput />
                </FieldBody>
            </Field>
            <Field Horizontal>
                <FieldLabel ColumnSize="ColumnSize.IsFull.OnTablet.Is2.OnDesktop">Address</FieldLabel>
                <FieldBody ColumnSize="ColumnSize.IsFull.OnTablet.Is10.OnDesktop">
                    <TextInput />
                </FieldBody>
            </Field>
        </FocusTrap>
    </CardBody>
</Card>
@code {
    bool focusTrapActive = false;
}

Best Practices

Blocking Focus

Use a focus trap only while a modal surface or similarly blocking interaction is active. Avoid overlapping or nested traps because they can create an unpredictable focus order or prevent keyboard users from escaping.

Predictable Focus

Move focus to a meaningful control when the trap opens and always provide an obvious keyboard-accessible way to leave the region. When the trap closes, restore focus to the control that triggered it.

API

See the API reference for the parameters, events, methods, and related types available to the components covered on this page.

On this page