実現したいこと
Component1をroot1に、Component2をroot2にという形で
2つのコンポーネントをそれぞれ異なるルートノードにレンダリングしたいのですが、
その際Component1の状態をComponent2にも反映させたいです。
前提
create react app を使用しています
発生している問題・エラーメッセージ
Component1の状態をComponent2に反映させるやり方がわかりません。
該当のソースコード
index.tsx
1const root1 = ReactDOM.createRoot( 2 document.getElementById("root1") as HTMLElement 3); 4root1.render( 5 <React.StrictMode> 6 <Component1 /> 7 </React.StrictMode> 8); 9 10const root2 = ReactDOM.createRoot( 11 document.getElementById("root2") as HTMLElement 12); 13root2.render( 14 <React.StrictMode> 15 <Component2 /> 16 </React.StrictMode> 17);
App.tsx
1import { useState } from "react"; 2import { Component1 } from "components/Component1"; 3import { Component2 } from "components/Component2"; 4 5function App() { 6 const [state, setState] = useState("default"); 7 return ( 8 <> 9 <Component1 10 changeState={(v: string) => setState(v)} 11 /> 12 <Component2 option={state} /> 13 </> 14 ); 15} 16export default App; 17
試したこと
上記の様に、祖先でuseStateを用いて子コンポーネントに状態を渡し、
各子コンポーネントを直接呼び出してレンダリングしてみましたが、
index.tsxの<Component2 />にprops.optionを指定せよと言われてしまいだめでした。
ご指南の程お願い致します。
補足情報(FW/ツールのバージョンなど)
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.9.5",
Portal を使うとか?
https://ja.legacy.reactjs.org/docs/portals.html

回答1件
あなたの回答
tips
プレビュー