LoginSignup
0
0

React18でReactDOM.renderを使ったらイベントが発火しない!?

Last updated at Posted at 2023-06-23

概要

先日、とあるハッカソンに参加し、chrome拡張を作ることになり、Reactを使いました。せっかくなのでReact18を使って作っていたのですが、popupとoptionページでなぜかonClickなどのイベントが発火しなかった。ビルド時にエラーや警告もなく、React18を使うことやChrome拡張を作るのは初めてだったので、Chrome拡張の仕様?(そんな訳ない!!)と思ってしまいました。ところがどっこいpnpm run watchをしたらこんな警告が出るではないか...

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

前提

  • Reactでchrome拡張を開発している
  • Webpackの設定を書いてpopupやoptionsのファイルをビルドするようにしている

バージョン

  • "react": "^18.2.0"
  • "react-dom": "^18.2.0"
  • "webpack": "^5.86.0"
  • "webpack-cli": "^5.1.4"
  • "webpack-merge": "^5.9.0"

症状

警告

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 を使用してください。新しい API に切り替えるまで、アプリは React 17 で実行されているかのように動作します。詳細については、こちらをご覧ください:https://reactjs.org/link/switch-to-createroot

解決策

解決策は非常に簡単!

ReactDOM.render(<Options />, document.getElementById('root'));

↑を↓に書き換えるだけ

const container = document.getElementById('root');
const root = createRoot(container!);
root.render(<Options />);

まとめ

create-react-appなどでプロジェクトを立てていればこんなことにはならなかったと思う。同じ過ちを犯さないように気をつけたい。

0
0
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
0
0