From 46468bc72923154b38cb8d84a86ba3e10ffb58ac Mon Sep 17 00:00:00 2001 From: Stefan Cameron Date: Mon, 27 Sep 2021 16:57:21 -0500 Subject: [PATCH] [#482] Fix SSR issues when accessing document object Fixes #482 --- .changeset/unlucky-frogs-push.md | 5 +++++ .github/pull_request_template.md | 2 ++ src/focus-trap-react.js | 5 ++++- 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 .changeset/unlucky-frogs-push.md diff --git a/.changeset/unlucky-frogs-push.md b/.changeset/unlucky-frogs-push.md new file mode 100644 index 00000000..a7016ccd --- /dev/null +++ b/.changeset/unlucky-frogs-push.md @@ -0,0 +1,5 @@ +--- +'focus-trap-react': patch +--- + +Fix SSR issues when accessing `document` object (#482) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 387aad70..cb6e0052 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -20,6 +20,8 @@ __Please leave this checklist in your PR.__ - E2E test coverage added/updated. - Prop-types added/updated. - Typings added/updated. +- Changes do not break SSR: + - Careful to test `typeof document/window !== 'undefined'` before using it in code that gets executed on load. - README updated (API changes, instructions, etc.). - Changes to dependencies explained. - Changeset added (run `yarn changeset` locally to add one, and follow the prompts). diff --git a/src/focus-trap-react.js b/src/focus-trap-react.js index 3cbca4d3..af98dc76 100644 --- a/src/focus-trap-react.js +++ b/src/focus-trap-react.js @@ -87,7 +87,10 @@ class FocusTrap extends React.Component { /** Update the previously focused element with the currently focused element. */ updatePreviousElement() { - const currentDocument = this.props.focusTrapOptions.document || document; + // SSR: careful to check if `document` exists before accessing it as a variable + const currentDocument = + this.props.focusTrapOptions.document || + (typeof document !== 'undefined' ? document : undefined); if (currentDocument) { this.previouslyFocusedElement = currentDocument.activeElement; }