前提
reactで各ボックスに付随したボタンをクリックするとそのボックス内容が表示・非表示する機能を作りたいです。
実現したいこと
<button>クリック1</button>
<p>テキスト1</p><button>クリック2</button>
<p>テキスト2</p><button>クリック3</button>
<p>テキスト3</p>・クリック1を押すと、テキスト1が表示/非表示になる
・クリック2を押すと、テキスト2が表示/非表示になる
・クリック3を押すと、テキスト3が表示/非表示になる
発生している問題・エラーメッセージ
エラーメッセージ
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:
該当のソースコード
import React, { useState } from "react";
import "./styles.css";
export const App = () => {
const textArr = ["テキスト1", "テキスト2", "テキスト3"];
const [open, setOpen] = useState(false);
const onClickOpen = (index) => {
setOpen(!open[index]);
};
return (
<>
{textArr.map((text, index) => {
return (
<div key={text}>
<button onClick={() => onClickOpen(index)}>クリック</button>
{open[index] && <p>{text}</p>}
</div>
);
})}
</>
);
};
試したこと
配列のindexを伴わないものは作成できました。
その場合、クリック1を押すと、テキスト2とテキスト3も開いてしまいます。
押したボタンのボックスに対してのテキストを表示・非表示したいので、indexで指定したいのですが、上手く動作しません。
わかる方教えていただきたいです。
補足情報(FW/ツールのバージョンなど)
コードサンドボックスを使用しています。
react 18.2.0
react-dom 18.2.0
react-scripts 4.0.0

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/09/11 06:07