One way to solve the
<header> dilemma would be to create a
<Header> component and include it in both
AboutPage. That works, but is there a better solution? Ideally there should only be one reference to the
<header> anywhere in our code.
When you look at these two pages what do they really care about? They have some content they want to display. They really shouldn't have to care what comes before (like a
<header>) or after (like a
<footer>). That's where layouts come in: they wrap a page in a component that then renders the page as its child. The layout can contain any content that's outside of the page itself. Conceptually, the final rendered document will be structured something like:
Let's create a layout to hold that
From now on we'll use the shorter
galias instead of
web/src/layouts/BlogLayout/BlogLayout.js and an associated test file. We're calling this the "blog" layout because we may have other layouts at some point in the future (an "admin" layout, perhaps?).
<header> from both
AboutPage and paste it in the layout instead. Let's take out the duplicated
<main> tag as well:
children is where the magic will happen. Any page content given to the layout will be rendered here. And now the pages are back to focusing on the content they care about (we can remove the import for
HomePage since those are in the Layout instead). To actually render our layout we'll need to make a change to our routes files. We'll wrap
AboutPage with the
BlogLayout, using a
Notice that the import statement uses
./src/layouts/BlogLayout. Being able to use just
srcis a convenience feature provided by Redwood:
srcis an alias to the
srcpath in the current workspace. So if you're working in
apiit points to
Back to the browser and you should see...nothing different. But that's good, it means our layout is working.
Why are things named the way they are?
You may have noticed some duplication in Redwood's file names. Pages live in a directory called
/pagesand also contain
Pagein their name. Same with Layouts. What's the deal?
When you have dozens of files open in your editor it's easy to get lost, especially when you have several files with names that are similar or even the same (they happen to be in different directories). Imagine a dozen files named
index.jsand then trying to find the one you're looking for in your open tabs! We've found that the extra duplication in the names of files is worth the productivity benefit when scanning for a specific open file.
If you're using the React Developer Tools plugin this also helps disambiguate when browsing through your component stack:
<Link>, let's have the title/logo link back to the homepage as per usual:
And then we can remove the extra "Return to Home" link (and Link/routes import) that we had on the About page: