Frontend/React

React 18에서 지원하지 않는 [ReactDOM.render]

섕걍 2022. 4. 6. 16:38

React 18로 업그레이드 된 후로 18버전을 쓰려고 한다.

이떄 ReactDOM.render는 지원하지 않기 때문

주의해서 사용하길!

ReactDOM.render를 쓰면 17을 쓰게된당~

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

 

Before

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { Router } from "react-router-dom";
import {
  RecoilRoot,
} from "recoil";

ReactDOM.render(
  <RecoilRoot>
    <App />
  </RecoilRoot>,
  document.getElementById("root")
);

 

After

import React from "react";
import ReactDOM from "react-dom/client";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App";
import { Router } from "react-router-dom";
import {
  RecoilRoot,
} from "recoil";

const reactNode = document.getElementById("root");

ReactDOM.createRoot(reactNode).render(
  <RecoilRoot>
    <App />
  </RecoilRoot>
);

 

이때 타입스크립트를 사용해서

reactNode에서 아래와 같은 문제가 생긴다

const reactNode: HTMLElement | null
Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element | DocumentFragment'.
  Type 'null' is not assignable to type 'Element | DocumentFragment'.ts(2345)

 

요렇게 타입 단언을 해주면 완료~~~

const reactNode = document.getElementById("root")!;

아니면 요렇게  as HTMLElement; 를 붙여준다

const reactNode = document.getElementById("root") as HTMLElement;

 

 
출처: 스택오버플로

https://stackoverflow.com/questions/63520680/argument-of-type-htmlelement-null-is-not-assignable-to-parameter-of-type-el

 

Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Element'. Type 'null' is not assignable to type 'E

I have index.html <body> <div id="portal"></div> <div id="root"></div> </body> and want to use the component below in separate porta...

stackoverflow.com