2
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 3 years have passed since last update.

React Routerについて

Posted at

始めに

本筆者はズブズブの素人であリます。学習用の記録であります。

##まずはインストール

npm install react-router-dom

インストール後はreact-dom-domをimportする。
BrowserRouter, Switch,Route,Link使用できる様にする。

//index.js
mport {
  BrowserRouter,
  Switch,
  Route,
  Link
} from "react-router-dom";

BrowserRouter

BrowserRouterのタグ内部でrouter機能が使用できる様になる。
BrowserRouterは1プロジェクトにつき1回しか使えません。
react-router関連のコンポーネントが全て入るように、かなり上の階層で使うことになる。

//index.js

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <>
         {/* ここにreact-router関連のコンポーネントを全て書く */}
      </>
    </BrowserRouter>
  </React.StrictMode>,
  rootElement
);

Route

  • ルーティング先のURLと、そのURLで表示したいコンポーネントを指定します。
  • pathで遷移先のURLしする。
  • componentで表示したいコンポーネントを指定します
  • exactでURL完全しないと画面遷移されない様にする。react-routerは実はURLが前方一致したコンポーネントを全て表示します。それを予防します。
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <>
         <Route path="/" component={APP}/>
      </>
    </BrowserRouter>
  </React.StrictMode>,
  rootElement
);

Link

  • LinkはHTMLのaタグと同じような役割。
  • toでリンク先を指定することでそこへ遷移できる。
  • レンダリングされるとaタグに変換する。の中にaタグは含めることができない。

fileの分割

上記の内容でroutingの設定を進めると冗長となり、可読性が悪くなる。その為、routing用のファイルを作成し、分割していく。

src/router/Public.js

import React from "react";
import { Route, Switch } from "react-router-dom";
import Auth from "../components/auth_componets/Auth";
import Main from "../components/layouts/Main";

const Public: React.FC = () => {
  return (
    <>
      <Switch>
        <Route exact path="/login" component={Auth} />
        <Route exact path="/" component={Main} />
      </Switch>
    </>
  );
};

export default Public;

分割したファイルをimportしてやる

import Public './router/Public';

const App: React.FC = () => {
  return (
    <BrowserRouter>
      <>
        <Header />
        <Container fixed>
          <Public />
        </Container>
        <Footer />
      </>
    </BrowserRouter>
  );
};

終わりに

react routerを学習していきました。routerのバリエーションや実践的な内容が増えればアップしていきます。

2
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
2
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?