Skip to content

Instantly share code, notes, and snippets.

@kenmori
Last active November 19, 2021 13:04
Show Gist options
  • Select an option

  • Save kenmori/56b3dbaa9f76bc574e36f7363bcea04f to your computer and use it in GitHub Desktop.

Select an option

Save kenmori/56b3dbaa9f76bc574e36f7363bcea04f to your computer and use it in GitHub Desktop.
[解決] react-router-dom v5 to v6 移行に伴いやること

[解決] react-router-dom v5 to v6 移行に伴いやること

error TypeError: Cannot read properties of undefined (reading 'pathname') at Router (index.js:194)

これは何かpathnameのところでエラーになっていると思ったが、実際は conected-redux-routerが出しているもの

そこを変える。

Permission.Route等権限を確認するコンポーネントでラップしている箇所

下記のこういうのを変更する

  <ReactRouter.Routes>
     <ReactRouter.Route
       element={<Members.Component />}
                        path={RouteEntity.RouteURI.Members}
                    />
                    <Permission.Route
                        component={CompanyInfoPage.Component}
                        exact
                        path={RouteEntity.RouteURI.Company}
                    />
                    <Permission.Route
                        component={Organization.Component}
                        exact
                        path={RouteEntity.RouteURI.Organization}
                    />

こういう風にやる

{
            path: 'a',
            element: <ReactRouterDom.Outlet />, // /aは何も表示しない場合 Outletでchildrenに処理を移らせる
            children: [
                {
                    path: ':id',
                    element: (
                        <>
                            <A.Component /> // /a/123143 で表示される
                            <ReactRouterDom.Outlet /> // /a/123143の後にpathがさらに続く場合、FragmentでラップしてOutletを入れる
                        </>
                    ),
                    children: [ 
                        {
                            path: 'edit',
                            element: <Edit.Component />
                        }
                    ]
                }
            ]
        }
  • childrenを作る場合はoutletを含む
  • 参照

useHistory

useHistoryはuseNavigateに変更

const history = ReactRouterDom.useHistory()
const history = ReactRouterDom.useNavigate()

権限のところ

何か

const routes = (path: string, profile: Entity.OwnProfile | null) => {
    return Permission.isPermitted(path, profile)
        ? [{path: "", element: </>}] : [
              {
                  path: '/',
                  element: <NotPermitted.Component />
              }
          ]
})

const Routes = () => { const location = ReactRouter.useLocation() const profile = ReactRedux.useSelector(AuthSelector.authProfileSelector) let element = ReactRouterDom.useRoutes(routes(location.pathname, profile)) return element }

...

    <ReactRouterDom.BrowserRouter>
        <Auth.Component>
<Routes />
        </Auth.Component>
    </ReactRouterDom.BrowserRouter>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment