0
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 1 year has passed since last update.

React Routerを使ってトップページを変更してみた

Last updated at Posted at 2023-06-18

やりたいこと

reactでは、パスを指定しないドメインのみのurl(http://localhost など)ではindex.tsx(App.tsx)が呼び出されることになりますが、このデフォルトのページを別のコンポーネントにしたい。

index.tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'

import { App } from './App'

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
)
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
)
App.tsx
import React from 'react'

import { PostsTop } from './components/posts/PostsTop'

export const App = () => {
  return (
         {/* PostsTop をトップページにしたい */} 
  )
}

手順

1. react-router-domをインストールする

「react-router-dom」というパッケージをインストールします。

$ yarn add react-router-dom

2. App.tsxに追記する。

BrowserRouterとRoutesで囲んだ中にRouteを記述する。

App.tsx
import React from 'react'
import { BrowserRouter, Routes, Route } from 'react-router-dom'

import { PostsTop } from './components/posts/PostsTop'

export const App = () => {
  return (
        <BrowserRouter>
          <Routes>
            <Route path='/' element={<PostsTop />} />
          </Routes>
        </BrowserRouter>
  )
}

以上で完成です。
urlをさらに変更したい場合は、App.tsxのRoteのpathパラメータを変更すればOKです。

補足

React Routerはv5からv6にアップデートされたことで、かなり書き方が変わっています。
「Switch」を使った下記のようなやり方はv5以前のやり方なので、注意しましょう。
(以下、公式ドキュメントの引用)

React Router v6 introduces a Routes component that is kind of like Switch, but a lot more powerful.

App.tsx
import React from 'react'
import { BrowserRouter, Switch, Route } from 'react-router-dom'

import PostsTop from './components/posts/PostsTop'

export const App = () => {
  return (
        <BrowserRouter>
         <Switch>
          <Route path="/" exact component={PostsTop} />
         </Switch>
        </BrowserRouter>
  )
}

参考

https://ralacode.com/blog/post/how-to-use-react-router/
https://reactrouter.com/en/6.13.0/upgrading/v5#upgrade-to-react-router-v6

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?