2
1

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.

LaravelにReact + TypeScript の開発環境を構築②

Posted at

この記事の目的

ルーティング

フロー

  • React側でTOP画面(home)と usersというページを作成する
  • Laravelのルートを修正する

React側でTOP画面(home)と usersというページを作成

tsディレクトリ配下にRouter.tsxを作成

resources/ts/Router.tsx
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { Home } from "./Home";
import { Users } from "./Users";

export const Router = () => {
    return (
        <BrowserRouter>
            <Routes>
                <Route path={`/`} element={<Home />} />
                <Route path={`/Users/`} element={<Users />} />
            </Routes>
        </BrowserRouter>
    );
};
resources/ts/Home.tsx
import { Link } from "react-router-dom";

export const Home = () => {
  return (
    <>
      <h1 className='text-red'>Laravel React+Typescript環境構築</h1>
      <div>
        ユーザー一覧はこちら<Link to={`/users/`}>こちら</Link>
      </div>
    </>
  );
};
resources/ts/Users.tsx
import { Link } from "react-router-dom";

export const Users = () => {
    return (
        <>
        <h1>ユーザー一覧ページ</h1>
        <div>
            <Link to={`/`}>ホームに戻る</Link>
        </div>
        </>
    );
};
resources/ts/App.tsx
import React from 'react';
import { Router } from "./router";

const App = () => {
    return (
        <Router />
    )
}

export default App

Laravelのルートを修正

現状だと各ページ遷移時にブラウザを再読み込みするとNOT Foundになるの。
直接アクセスしても読み込まれるように修正する。/以外のルートを設定していないため

routes/web.php
// どのURLにアクセスしても1つのページindex.phpがレンダリングされるように設定します。
Route::get('{any}', function () {
  retrun view('index');
})->where(['any' => '.*']);

  • /{any}に合致した時に、index.phpがレンダリングされる。(つまり/の後に何が来ても)
  • where('any', '.*')ですべてのURLでヒットするようになる。
2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?