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
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
本文标签: reactjsHow to pass props to Layout component in Remix 3Stack Overflow
版权声明:本文标题:reactjs - How to pass props to Layout component in Remix 3? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744141902a2592656.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论