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
1 Answer
Reset to default 0I 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
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744141903a4560242.html
评论列表(0条)