0
0

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.

特定のclassのあるエレメントにReactのアプリを表示したい

Posted at

なぜ特定のクラスにReactのアプリを出したいのか?

通常、Reactは<div id="root"></div>というところにアプリを描画します。
index.htmlには上記divだけ置いて、SPAとして処理を行うことが多いでしょう。

ところが、レガシーなPHPに組み込む際、どうしてもReactを複数個所に設置したいときがあります。

たとえば、TODOリストを想像してください。
複数リストがあります。
そのリストの一番右にボタンをつくりたいわけです。
そのボタンを押したときの処理を含めて、Reactでつくりたい。

どうすれば良いのか

main.tsx
const elements = document.querySelectorAll(".target-class");

elements.forEach((element) => {
  ReactDOM.createRoot(element).render(<App />);
});

こうですね!
いつも1回しかReactDOM.createRootをしないと思いますが、elementsで拾ったところに出せば大丈夫です。

しかし邪道だと思うので、そもそもpreactとかlitでweb componentsにするべきでしょうな。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?