简体   繁体   中英

Passing props to child component with react-router v6

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 /> ?

The best way to deal with this situation is by using outlet context .

In the parent component pass context via Outlet .

// parent.ts
const Parent = () => {
  const firstName = 'John'
  const lastName = 'Doe'

  return (
    <h1>Parent Component</h1>
    <Outlet context=[firstName, lastName]/> // How to pass the appropriate props?
  )
}

Then, in the children components, get those context data using useOutletContext hook.

import { useOutletContext } from "react-router-dom";
export const Child1 = () => {
  const [firstName] = useOutletContext();
  return (
    <h2>First Name</h2>
    {props.firstName}
  )
}

export const Child2 = () => {
  const [lastName] = useOutletContext();
  return (
    <h2>Last Name</h2>
    {props.lastName}
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM