useRoutes() を使って作成します。Vue-Router に少し近い記述になります。
npx create-react-app my-router-ts-app --template typescript
cd my-router-ts-app
yarn add react-router-dom
yarn add @types/react-router-dom
src/App.tsx を以下のようにします
import "./App.css";
import { BrowserRouter } from "react-router-dom";
import Router from "./router";
function App() {
return (
<BrowserRouter>
<div className='App'>
<h1>Vite + React !</h1>
<hr />
<Router></Router>
</div>
</BrowserRouter>
);
}
export default App;
src/router/index.tsx を以下の内容で作成します
import { useRoutes } from "react-router-dom";
import Login from "../views/Login";
import About from "../views/About";
export default function Router() {
return useRoutes([
{
path: "/",
element: <DefaultLayout />,
children: [{ path: "about", element: <About /> }],
},
{
path: "/",
element: <GuestLayout />,
children: [{ path: "login", element: <Login /> }],
},
]);
}
src/views/About.tsx
import React from "react";
import { Link } from "react-router-dom";
const About: React.FC = () => {
return (
<div>
<h1>About</h1>
<p>テストテキストテストテキストテストテキスト</p>
<Link to='/'>戻る</Link>
</div>
);
};
export default About;
src/views/Login.tsx
import React from "react";
import { Link } from "react-router-dom";
const Login: React.FC = () => {
return (
<div>
<h1>Login</h1>
<p>ログイン画面です。</p>
<Link to='/'>戻る</Link>
</div>
);
};
export default Login;
これで、次のURLへアクセスできます。
http://localhost:3000/about
http://localhost:3000/login
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
<button type='button' onClick={() =>{ navigate(-1) }}>戻る</button>
https://zukucode.com/2021/06/react-router-razy.html
https://dev-yakuza.posstree.com/react/create-react-app/react-router/
https://stackoverflow.com/questions/69843615/switch-is-not-exported-from-react-router-dom
import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/home');
function PrivateRoute ({component: Component, authed, ...rest}) {
return (
<Route
{...rest}
render={(props) => authed === true
? <Component {...props} />
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
/>
)
}
<Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />
参考 : https://blog.logrocket.com/complete-guide-authentication-with-react-router-v6/