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?

ナビゲーション

Last updated at Posted at 2024-06-18
// 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;

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?