WEB/React

Warning: ReactDOM.render is no longer supported in React 18. Use createRoot instead.

Harimad 2022. 4. 12. 15:14

에러

리액트 버전 18에서 npm run dev를 했는데, 다음과 같은 에러 메세지가 콘솔창에 나타났다.

Warning: 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 

원인

ReactDOM.render가 React 18에서 더이상 쓸 수 없어졌고, createRoot 대신 사용해야 한다고 나와있다.

 

해결

그래서 경고창의 링크를 타고들어가서 아래와 같이 바꿔줬다.

// 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" />);

import 안의 render 프로퍼티가 createRoot 로 바뀌었다.

 

이전에는 render() 메서드안에 인자로 컴포넌트와 삽입할 html 태그를 넣었다.

이제는 createRoot() 메서드 안에 삽입할 html 태그를 인자로 넣어서

render()메서드를 이용해 React 요소를 DOM으로 변환시킨다.

 

참고

https://ko.reactjs.org/docs/concurrent-mode-reference.html#concurrent-mode

 

createRoot()