Arijit
Arijit

Reputation: 134

How to use React router v6.4 with typescript properly?

I'm trying to use react-router-dom v6.4+ in my project. I implemented it as a route array of objects. Its worked as routing but suddenly I got another issue realated this. I can't call any hook inside the Component which located on element property in route array.
In the route.ts file:

import MainLayout from './container/layouts/mainLayout/MainLayout'
import ErrorPage from './view/Error'
import Home from './view/Home'

const routes: RouteObject[] = [
  {
    path: '/',
    element: MainLayout(),
    children: [
      {
        index: true,
        element: Home(),
      },
    ],
  },
  {
    path: '*',
    element: ChangeRoute('/404'),
  },
  {
    path: '/404',
    element: ErrorPage(),
  },
]

const router = createBrowserRouter(routes)

export default router

and in the app.ts file:

<RouterProvider router={router} fallbackElement={<React.Fragment>Loading ...</React.Fragment>} />

But If I try to use any hook , inside MainLayout component , its saying
this error in console

code in MainLayout component :

const MainLayout = () => {
  const [collapsed, setCollapsed] = useState(false)

  return (
    <Layout className='layout'>
      <SideBar collapsed={collapsed} />
      <Layout>
        <Topbar collapsed={collapsed} setCollapsed={setCollapsed} />
        <Outlet />
      </Layout>
    </Layout>
  )
}

export default MainLayout

I think if I use element: <MainLayout/> instead of element: MainLayout(), then this issue will resolve. but typescript doesnt allow me to do this. and on the documentation every thing is on plain javascript. only one type defination there is this

How to solve this? Kindly guide me.

Edit Here is the codesandbox demo : visit sandbox

Upvotes: 3

Views: 7290

Answers (2)

ovct
ovct

Reputation: 101

Changes the name of the route.ts file to route.tsx, now you can will set components in the element object property, this works for me.

Upvotes: 10

Drew Reese
Drew Reese

Reputation: 202648

The element prop expects a React.ReactNode, you are directly calling a React function instead of passing it as JSX.

Example:

const routes: RouteObject[] = [
  {
    path: '/',
    element: <MainLayout />,
    children: [
      {
        index: true,
        element: <Home />,
      },
    ],
  },
  {
    path: '*',
    element: <ChangeRoute redirect='/404' />,
  },
  {
    path: '/404',
    element: <ErrorPage />,
  },
]

Upvotes: 1

Related Questions