LoginSignup
3
0
お題は不問!Qiita Engineer Festa 2024で記事投稿!
Qiita Engineer Festa20242024年7月17日まで開催中!

モーダルを開いても正しい内容が表示されない!?

Last updated at Posted at 2024-06-13

はじめに

モーダルを開くボタンを複数表示させたのはいいけれど、どのボタンをクリックしてもモーダルに表示されるコンテンツが同じになってしまう…。そんな時はコンテンツを識別するidをモーダルに渡してあげよう!

コードサンプル


  const [loading, setLoading] = useState(false);
  const [hogeDatas, setHogeDatas] = useState([]);
  const [isModalOpen, setIsModalOpen] = useState(false);

    async function openModal(id) {
      setLoading(true);

      await UseAxios('get', 'hogehoge')
        .then(function (res) {
          if (res && res.data && res.data.response) {
            let d = datas.filter((data) =>
              res.data.response.dataIds.includes(data.id)
            );
            setHogeDatas(d);
            setIsModalOpen(true);
            setLoading(false);
          }
        })
        .catch(function (error) {
          console.log(error);
          console.log(error.response);
          setLoading(false);
        });
    }


  function Content() {
  // モーダル内で表示させたいデータと対応するid
    return filterHoges.map((hoge) => {
      let idx = hoge.id;
    
        onClick={() => openModal(idx)}
    }

  return (
    <Content></Content>
    )

おわりに

idなどを渡してあげないと、非同期で取得し終わった最後のコンテンツがどのモーダルにも表示されることになります。

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