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?

More than 1 year has passed since last update.

React + MUI + react-router-dom でNavigatorを作る

Last updated at Posted at 2023-02-28

環境

  • React
  • MUI
  • react-router-dom

完成図

左側のナビゲーターで、現在いるページを強調表示したかったのです。

image.png

参考にしたサンプル

コード

元だと、リンク先に飛ばす仕組みと、遷移後に強調表示する仕組みがなかったので追加します。

ListItemButtonのActiveをtrueにしたいので、
location = useLocation()
で取得したlocationのpathnameと、リンク(to)を比較してください。

useLocationの呼び出し位置
export default function Navigator(props) {
  const { ...other } = props

  const location = useLocation()

  return (

そしてReact + MUIだとメニューはListItemやListItemButtonを使って作ると思います。
ListItemにNavLinkを組み合わせるには
component={NavLink}を指定します。

jsx
<ListItem  key={childId} disablePadding component={NavLink}
to={to}>
    <ListItemButton
        selected={location.pathname===to}
        sx={item}
    >
        <ListItemIcon>{icon}</ListItemIcon>
        <ListItemText>{childId}</ListItemText>
    </ListItemButton>
</ListItem>

クリックしたら元データのactiveプロパティをfalseにして・・とか考えてたんですけどよく考えたら現在のURLと比較するだけだったのでメモをのこしておきます。

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?