10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

TypescriptとReact 18の環境でcreateRootのエラー除去

Posted at

Typescript と React 18 の環境で、createRootにて
Property 'createRoot' does not exist on type のエラーを取る方法がわからなかったので、いろいろ調べた結果、公式が一番良かった。

Typescript 初心者なので全然わからなかったが、ちょっと、かじった人ならすぐわかるんだろうなぁ。

Create React App: で Typescriptベースのテンプレートを作成する。
createRootを使うように修正する。
rootElement がnull になる対策だけを入れたが、createRoot でエラー発生。

対策前

index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const rootElement = document.getElementById('root');
// https://blog.logrocket.com/how-to-use-typescript-with-react-18-alpha/
if (!rootElement) throw new Error('Failed to find the root element');
const root = ReactDOM.createRoot(rootElement);
root.render(<App/>);

対策後

index.tsx
import React from 'react';
// https://reactjs.org/docs/react-dom-client.html
import * as ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const rootElement = document.getElementById('root');
// https://blog.logrocket.com/how-to-use-typescript-with-react-18-alpha/
if (!rootElement) throw new Error('Failed to find the root element');
const root = ReactDOM.createRoot(rootElement);
root.render(<App/>);
10
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?