Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/neat-sheep-cheer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'focus-trap-react': minor
---

Delay trap creation until it should be active. This is a change in behavior, however it should not break existing behavior. The delay now allows you to set `active=false` until you have the `focusTrapOptions` set correctly. [#539](https://github.com/focus-trap/focus-trap-react/issues/539)
29 changes: 25 additions & 4 deletions src/focus-trap-react.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,14 @@ class FocusTrap extends React.Component {
}

componentDidMount() {
this.setupFocusTrap();
if (this.props.active) {
this.setupFocusTrap();
}
// else, wait for later activation in case the `focusTrapOptions` will be updated
// again before the trap is activated (e.g. if waiting to know what the document
// object will be, so the Trap must be rendered, but the consumer is waiting to
// activate until they have obtained the document from a ref)
// @see https://github.com/focus-trap/focus-trap-react/issues/539
}

componentDidUpdate(prevProps) {
Expand Down Expand Up @@ -203,9 +210,23 @@ class FocusTrap extends React.Component {
if (hasUnpaused) {
this.focusTrap.unpause();
}
} else if (prevProps.containerElements !== this.props.containerElements) {
this.focusTrapElements = this.props.containerElements;
this.setupFocusTrap();
} else {
// NOTE: if we're in `componentDidUpdate` and we don't have a trap yet,
// it either means it shouldn't be active, or it should be but none of
// of given `containerElements` were present in the DOM the last time
// we tried to create the trap

if (prevProps.containerElements !== this.props.containerElements) {
this.focusTrapElements = this.props.containerElements;
}

// don't create the trap unless it should be active in case the consumer
// is still updating `focusTrapOptions`
// @see https://github.com/focus-trap/focus-trap-react/issues/539
if (this.props.active) {
this.updatePreviousElement();
this.setupFocusTrap();
}
}
}

Expand Down