React 18でReactDOM.render is no longer・・・というエラーが出るときの対処法
※本ページはプロモーションが含まれています
公開日:

React17から18にアップデートしたところ、
ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it’s running React 17. Learn more: https://reactjs.org/link/switch-to-createroot
というエラーが出ていました。
React18から、新しいroot APIができ、render方法が変わったのが原因です。
// Before
import { render } from 'react-dom';
const container = document.getElementById('app');
render(<App tab="home" />, container);
// After
import { createRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App tab="home" />);
getElementByIdの返り値はnullである可能性があるので、Typescriptだとエラーが出るためcontainerをチェックする。
import { createRoot } from 'react-dom/client';
const container = document.getElementById('app');
if ( container ) {
const root = createRoot(container);
root.render(<App tab="home" />);
}
