@2023/12/02 React v16環境を構築する
React v18が当たり前になりつつある時代にあえてReact v16環境構築が必要な方向けの参考になれば・・・。 いろいろと事情があり、手元でReact v16環境を作って検証したいことが出来たので、手っ取り早くReact v16環境を手に入れる方法をメモしておく。(2023/12/02 現在の情報)
TL;DR;
create-react-appで初期構築する
以下のスクリプトを実行した
code:shell
npx create-react-app@3.4.1 my-app --template typescript
Reactのバージョンをダウングレードする
以下のスクリプトを実行し、react-domのrender部分を少し修正することで起動できた
code:shell
# yarn や pnpm は読み替えてください
npm i -S react@^16.0.0 react-dom@^16.0.0 @types/react@^16.0.0 @types/react-dom@^16.0.0 @testing-library/react@^12.0.0
code:diff
% git diff
diff --git a/package.json b/package.json
index 01b0cab..f497fab 100644
--- a/package.json
+++ b/package.json
@@ -4,14 +4,14 @@
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.14.1",
- "@testing-library/react": "^13.0.0",
+ "@testing-library/react": "^12.1.5",
"@testing-library/user-event": "^13.2.1",
"@types/jest": "^27.0.1",
"@types/node": "^16.7.13",
- "@types/react": "^18.0.0",
- "@types/react-dom": "^18.0.0",
- "react": "^18.2.0",
- "react-dom": "^18.2.0",
+ "@types/react": "^16.14.52",
+ "@types/react-dom": "^16.9.24",
+ "react": "^16.14.0",
+ "react-dom": "^16.14.0",
"react-scripts": "5.0.1",
"typescript": "^4.4.2",
"web-vitals": "^2.1.0"
diff --git a/src/index.tsx b/src/index.tsx
index 032464f..374ca47 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -1,16 +1,16 @@
import React from 'react';
-import ReactDOM from 'react-dom/client';
+import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
-const root = ReactDOM.createRoot(
- document.getElementById('root') as HTMLElement
-);
-root.render(
- <React.StrictMode>
- <App />
- </React.StrictMode>
+ReactDOM.render(
+ (
+ <React.StrictMode>
+ <App />
+ </React.StrictMode>
+ ),
+ document.getElementById('root')
);
---
メモ
create-react-appは、実行時の最新のReact等をインストール対象としてしまう(*1)ため、環境作成後にダウングレードを行う。今回は、一応create-react-appをReact v16当時のバージョンで実行して環境構築した。
*1
このあたり。バージョン未指定のReactをインストールするため、自動的に実行時の最新になる模様。