// 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;
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme