Skip to content

Commit

Permalink
[#539] Delay trap creation until it should be active (#546)
Browse files Browse the repository at this point in the history
Fixes #539
  • Loading branch information
stefcameron authored Dec 11, 2021
1 parent 49a6c0d commit 83097a5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
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

0 comments on commit 83097a5

Please sign in to comment.