Skip to content

Commit 83097a5

Browse files
authored
[#539] Delay trap creation until it should be active (#546)
Fixes #539
1 parent 49a6c0d commit 83097a5

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

.changeset/neat-sheep-cheer.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'focus-trap-react': minor
3+
---
4+
5+
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)

src/focus-trap-react.js

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,14 @@ class FocusTrap extends React.Component {
172172
}
173173

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

178185
componentDidUpdate(prevProps) {
@@ -203,9 +210,23 @@ class FocusTrap extends React.Component {
203210
if (hasUnpaused) {
204211
this.focusTrap.unpause();
205212
}
206-
} else if (prevProps.containerElements !== this.props.containerElements) {
207-
this.focusTrapElements = this.props.containerElements;
208-
this.setupFocusTrap();
213+
} else {
214+
// NOTE: if we're in `componentDidUpdate` and we don't have a trap yet,
215+
// it either means it shouldn't be active, or it should be but none of
216+
// of given `containerElements` were present in the DOM the last time
217+
// we tried to create the trap
218+
219+
if (prevProps.containerElements !== this.props.containerElements) {
220+
this.focusTrapElements = this.props.containerElements;
221+
}
222+
223+
// don't create the trap unless it should be active in case the consumer
224+
// is still updating `focusTrapOptions`
225+
// @see https://github.com/focus-trap/focus-trap-react/issues/539
226+
if (this.props.active) {
227+
this.updatePreviousElement();
228+
this.setupFocusTrap();
229+
}
209230
}
210231
}
211232

0 commit comments

Comments
 (0)