LoginSignup
0
0

react-router-dom v6でのnavigateで現在のパスから相対的な移動をしてしまう

Last updated at Posted at 2024-05-11

概要から解決まで

react-router-dom v6 のuseNavigateの返り値navigateでパスを指定しても、現在のパスからの相対的な移動になってしまう。この解決方法で詰まったので記事に残す。

以下、簡易的なコード(面倒なのでRouterを使っていないがコメントから察してほしい)
以下のようにContactコンポーネント内からProfileのパスを指定して移動する時、navigateの最初には/を付けておく必要がある

// path is '/'
const Home = () => {
  return (
    <>
      {/* path is 'contact' */}
      <Contact />
      {/* path is 'profile' */}
      <Profile />
    </>
  )
}

const Contact = (): JSX.Element => {
  const navigate = useNavigate()
  const handleClick = () => {
    // navigate('profile') ← 最初に`/`をつけておく必要がある。このままだと /contact/profile に飛んでしまう
    navigate('/profile')
  }
  return (
    <button type="button" onClick={handleClick}>
      Go to profile
    </button>
  )
}

const Profile = (): JSX.Element => {
  return <div>Profile</div>
}
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