Upgrading to React 18

This is a reminder that I had a festival at work to upgrade from React 16 or 17 -> React 18.
Please refer to the official documentation “How to Upgrade to React 18”.
1. Upgrade to React 18
There are about three ways to do this. (There are probably more.) 1.
1.npm install react react react-dom
1.
1.yarn add react react react-dom
1.
1.yarn upgrade react react-dom @types/react @types/react-dom --latest
1.
The official article introduces 1,2.
2. rewriting index.tsx
React 18 requires an update to the Client Rendering APIs.
Specifically, ReactDom.reder
is not supported in React 18.
“typescript
// React 17 and earlier
import ReactDom from “react-dom”;
import App from “. /App”;
ReactDom.render(, document.getElementById(“app”));
typescript
// React 18 or later
import ReactDOM from “react-dom/client”;
import App from “. /App”;
const container = document.getElementById(“app”);
if (container) {
root.render();
}
Alternatively, you can use
`typescript
import { createRoot } from ‘react-dom/client’;
const container = document.getElementById(‘app’);
const root = createRoot(container); // createRoot(container!) if you use TypeScript
root.render();
““
The first one needs to be rewritten as ```. The second one is official. It looks like you need to write
container!` because TypeScript’s non-null warning is output.
3. Rewriting React.FC
If your project uses TypeScript, you will need to update your @types/react and @types/react-dom dependencies to the latest versions. The new types are The most notable change is that the children prop now needs to be listed explicitly when The most notable change is that the children prop now needs to be listed explicitly when defining props, for example:
As above, children props must be explicitly passed.
// before React 18 const HogeComponent: React.FC = () => {} return ( <HogeComponent> <div> hoge </div> </HogeComponent> )
// React 18以降 interface HogeProps { children: React.ReactNode } const HogeComponent = (props: HogeProps) => {} return ( <HogeComponent> <div> hoge </div> </HogeComponent> )
4. TypeScript の型エラー修正
TypeScriptのバージョンを上げたので、Class を使用している場合は型エラーが起きる場合があります。