Passing props to child component with react-router v6

Viewed 954

I am using React Router v6 with all routes in a single config file, hence, making use of <Outlet /> to render the child. However I don't know how to pass the appropriate props depending on the component that matches when having my routes in a separate config file.

// route.ts
export const routes = [
  {
    path: '/*',
    element: <Parent />,
    children: [
      {
        path: 'child1',
        elements: <Child1 />, // Typescript complains: Property 'firstName' is missing in type '{}' but required in type 'IProps'
      },
      {
        path: 'child2',
        elements: <Child2 />, // Property 'lastName' is missing in type '{}' but required in type 'IProps'
      }
    ]
  }
]
// App.ts
const App = () => {
  const _routes = useRoutes(routes)
  return _routes
}
// Parent.ts
const Parent = () => {
  const firstName = 'John'
  const lastName = 'Doe'

  return (
    <h1>Parent Component</h1>
    <Outlet /> // How to pass the appropriate props?
  )
}
interface IFirstNameProps {
  firstName: string
}

interface ILastNameProps {
  lastName: string
}

export const Child1 = (props: IProps) => {
  return (
    <h2>First Name</h2>
    {props.firstName}
  )
}

export const Child2 = (props: IProps) => {
  return (
    <h2>Last Name</h2>
    {props.lastName}
  )
}

Using the <Route> component it would be something like this:

const Parent = () => {
  const firstName = 'John'
  const lastName = 'Doe'

  return (
    <Route path='child1' element={
      <Child1 firstName={firstName} />
    } />
    <Route path='child2' element={
      <Child2 lastName={lastName} />
    } />
  )
}

How can I achieve the same thing with a routes.ts config file and <Outlet />?

0 Answers
Related