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?

ナビゲーション実装

Posted at
// BottomNavigationComponent.js
import React, { useEffect, useState } from 'react';
import { BottomNavigation, BottomNavigationAction } from '@mui/material';
import { useLocation, useNavigate } from 'react-router-dom';
import HomeIcon from '@mui/icons-material/Home';
import SearchIcon from '@mui/icons-material/Search';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';

const BottomNavigationComponent = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const [value, setValue] = useState(0);

  // パスと対応するインデックスをマッピングする関数
  const pathToIndex = {
    '/': 0,
    '/search': 1,
    '/profile': 2,
  };

  useEffect(() => {
    // 現在のパスを基にBottom Navigationのインデックスを設定
    const currentPath = location.pathname;
    if (pathToIndex.hasOwnProperty(currentPath)) {
      setValue(pathToIndex[currentPath]);
    }
  }, [location.pathname]); // location.pathnameが変わる度に実行される

  const handleChange = (event, newValue) => {
    setValue(newValue);
    // インデックスに対応するパスにナビゲート
    const indexToPath = Object.keys(pathToIndex).find(
      (key) => pathToIndex[key] === newValue
    );
    if (indexToPath) {
      navigate(indexToPath);
    }
  };

  return (
    <BottomNavigation value={value} onChange={handleChange}>
      <BottomNavigationAction label="Home" icon={<HomeIcon />} />
      <BottomNavigationAction label="Search" icon={<SearchIcon />} />
      <BottomNavigationAction label="Profile" icon={<AccountCircleIcon />} />
    </BottomNavigation>
  );
};

export default BottomNavigationComponent;
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?