admin管理员组

文章数量:1399911

I have a heading in Layout and I want to pass props to it. So I can start my <main> element.

Here is my Layout.tsx

<>
  <h1>{title}</h1>
  <main>
    <Outlet /> {/* children */}
  </main>
  <Footer />
</>

Here is my routes.ts

export default [
  layout('./layouts/Layout.tsx', [
    index('./pages/index.tsx'),
    route('product', './pages/product.tsx'),
    route('contact', './pages/contact.tsx'),
  ]),
] satisfies RouteConfig;

So I can have my page with pre-headding. E.g. about.tsx

<>
  <h2>Who are we</h2>
<>

I have a heading in Layout and I want to pass props to it. So I can start my <main> element.

Here is my Layout.tsx

<>
  <h1>{title}</h1>
  <main>
    <Outlet /> {/* children */}
  </main>
  <Footer />
</>

Here is my routes.ts

export default [
  layout('./layouts/Layout.tsx', [
    index('./pages/index.tsx'),
    route('product', './pages/product.tsx'),
    route('contact', './pages/contact.tsx'),
  ]),
] satisfies RouteConfig;

So I can have my page with pre-headding. E.g. about.tsx

<>
  <h2>Who are we</h2>
<>
Share Improve this question edited Mar 26 at 17:08 Drew Reese 204k18 gold badges244 silver badges273 bronze badges asked Mar 26 at 13:17 marutpunmarutpun 632 silver badges8 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 0

I think I've found the answer (myself). But I'm not sure whether it's right or wrong.

Use handle in child component and useMatches in parent component.

First, export handle object.

// pages/about.tsx
export const handle = {
  pageTitle: 'About Us',
  pageDescription: 'Learn more about our history'
};

function AboutPage() {
  return <h2>Who are we</h2>
}

Then, useMatches in <Layout>

// layouts/Layout.tsx
import { Outlet, useMatches, type UIMatch } from 'react-router';

export default function Layout() {
  const matches: UIMatch[] = useMatches();

  const childHandle = matches.filter((match) => match.handle);
  const { handle } = childHandle[0] || {};

  console.log(handle);
// {
//  pageTitle: 'About Us',
//  pageDescription: 'Learn more about our history'
// }

  return (
    <>
      <Navbar />
      {handle?.pageTitle && <h1>{handle.pageTitle}</h1>}
      {handle?.pageDescription && <p>{handle.pageDescription}</p>}
      <Outlet />
      <Footer />
    </>
  );
}

Ref: Sharing data between nested routes in Remix

本文标签: reactjsHow to pass props to Layout component in Remix 3Stack Overflow