Skip to content

Load react-dom correctly based on React version #1269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 6, 2023
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ _Please add entries here for your pull requests that are not yet released._

#### Bug Fixes
- Fix installation crash caused by absolute path for `source_entry_path` in default `config/webpacker.yml` coming from `shakapacker` version 6.x - #1216
- Fix warning for loading `react-dom` in React 18 - #1269

## 2.6.2

Expand Down
24 changes: 24 additions & 0 deletions react_ujs/src/reactDomClient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import ReactDOM from "react-dom"

const reactMajorVersion = ReactDOM.version?.split('.')[0] || 16

// TODO: once we require React 18, we can remove this and inline everything guarded by it.
const supportsRootApi = reactMajorVersion >= 18

let reactDomClient = ReactDOM

if (supportsRootApi) {
// This will never throw an exception, but it's the way to tell Webpack the dependency is optional
// https://github.com/webpack/webpack/issues/339#issuecomment-47739112
// Unfortunately, it only converts the error to a warning.
try {
// eslint-disable-next-line global-require,import/no-unresolved
reactDomClient = require('react-dom/client');
} catch (e) {
// We should never get here, but if we do, we'll just use the default ReactDOM
// and live with the warning.
reactDomClient = ReactDOM;
}
}

export default reactDomClient
2 changes: 1 addition & 1 deletion react_ujs/src/renderHelpers.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import ReactDOM from "react-dom"
import ReactDOM from "./reactDomClient"

export function supportsHydration() {
return typeof ReactDOM.hydrate === "function" || typeof ReactDOM.hydrateRoot === "function"
Expand Down