LoginSignup
0
0

More than 3 years have passed since last update.

Reactルータ

Posted at

Reactのルーターについての基本!!

基本形

import React from "react";
import { Link } from "react-router-dom";

export default function App() {
  return (
    <div>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
      <Link to="/users">Users</Link>
    </div>
  );
}

コンポーネント

:exclamation:全てreact-router-domからimportする必要がある:helmet_with_cross:

1. routers

:point_up_tone1: <BrowserRouter>: 通常のURLパスを使用
:point_up_tone1: <HashRouter>: URLにhashを含むパスを使用(e.g. http://example.com/#/your/page)

2. Route Matchers

:point_up_tone1:<Switch>の中で<Route>を使う。現在のページが<Route>に記載されているページと同じならページ遷移しない。

:anchor:ポイント:anchor:
途中まで同じURLの時はより詳細の方を先に書く
:warning:Route exact path=を使えば書く順番は問わない。

<Route path="/contact/:id">
  <Contact />
</Route>
<Route path="/contact">
  <AllContacts />
</Route>

3. Navigation

:point_up_tone1:<NavLink>: パスが変わらなくても押せばアクティブになる

Scroll

:point_up_tone1: <ScrollToTop>TOPにスクロール

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}
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