// 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';
// Define the type
type PathToIndexType = {
path: string;
name: string;
};
// Create the array and ensure it's typed correctly
const pathToIndex: PathToIndexType[] = [
{ path: '/', name: 'Home' },
{ path: '/search', name: 'Search' },
{ path: '/profile', name: 'Profile' },
];
const BottomNavigationComponent = () => {
const location = useLocation();
const navigate = useNavigate();
const [value, setValue] = useState<number>(0);
useEffect(() => {
// 現在のURLパスを取得
const currentPath = location.pathname;
// パスに対応するインデックスを取得
const index = pathToIndex.findIndex((item) => item.path === currentPath);
// インデックスが見つかれば、valueを更新
if (index !== -1) {
setValue(index);
}
}, [location.pathname]); // location.pathnameが変わる度に実行される
const handleChange = (event: React.SyntheticEvent, newValue: number) => {
setValue(newValue);
const selectedPath = pathToIndex[newValue]?.path;
if (selectedPath) {
navigate(selectedPath);
}
};
return (
<BottomNavigation value={value} onChange={handleChange}>
{pathToIndex.map((item, index) => (
<BottomNavigationAction
key={item.path}
label={item.name}
icon={
index === 0 ? (
<HomeIcon />
) : index === 1 ? (
<SearchIcon />
) : (
<AccountCircleIcon />
)
}
sx={{ color: value === index ? 'primary.main' : 'inherit' }}
/>
))}
</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