
Building layout and styling pages
In this part, we are focusing on adding the missing layout parts and styling the blog
Introduction
In the previous article we created the Article service and we add some basic styling to it. This is a good starting point, but our page is still far from looking good and looking like a functioning website at all. There is no navigation, no footer and no homepage. We are going to tackle all of these problems in this article. Please remember to create a new branch for the changes we are about to do today.
Updating layout
Our pages need a frame which ensures that everything on the page is displayed properly, like for example centered on the page, with a proper header with the logo and navigation and a footer at the bottom of each page with social media links, general conditions, contact data or whatever else is needed.
Header
We are going to start by creating a Header component which will contain of a logo and some navigation links to our main pages. For this purpose we create Header.tsx, Header.test.tsx, Header.scss and index.tsx in src/components. Our Header component can have structure like this:
1import Link from 'next/link';
2import { ARTCILES_ROUTE } from '@/constants';
3import './Header.scss';
4type NavLink = {
5 name: string;
6 href: string;
7};
8const navLinks: NavLink[] = [
9 { href: '/', name: 'Home' },
10 { href: ARTCILES_ROUTE, name: 'Articles' },
11];
12export function Header() {
13 return (
14 <header className="Header">
15 <Link href="/" className="logo">
16 <h1>My Blog</h1>
17 </Link>
18 <nav className="links">
19 {navLinks.map(({ href, name }) => (
20 <Link key={href} href={href} className="HeaderLink">
21 {name}
22 </Link>
23 ))}
24 </nav>
25 </header>
26 );
27}We have here the h1 which will serve as a logo (I want the product of this course to be a template which anyone can easily customize). We also have links to our main pages which in our case are just homepage and articles page. Not only that, but we should also add some testing to ensure everything works as expected. I think for such a simple component, one general test is enough.
1import { render, screen } from '@testing-library/react';
2import { Header } from './Header';
3describe('Header', () => {
4 it('should render properly', () => {
5 render(<Header />);
6 const links = screen.getAllByRole('link');
7 expect(links.length).toBe(3);
8 expect(links[1].textContent).toBe('Home');
9 expect(links[2].textContent).toBe('Articles');
10 });
11});Furthermore, we have to export this new component, so we can use it in the layout. To do so export it from both components/Header/index.tsx and components/index.tsx.
1export { Header } from './Header';Now the new component can be applied to the layout.tsx so we can see it on the page and style it.
1import type { Metadata } from 'next';
2import { Header } from '@/components';
3import './globals.scss';
4export const metadata: Metadata = {
5 title: 'Next.js Markdown Blog',
6 description:
7 'This is a blog/portfolio website built using Nextjs 13 in which all the content is stored as markdown files.',
8};
9export default function RootLayout({
10 children,
11}: Readonly<{
12 children: React.ReactNode;
13}>) {
14 return (
15 <html lang="en">
16 <body>
17 <Header />
18 <main>{children}</main>
19 </body>
20 </html>
21 );
22}Let's commit the changes to not lose track of our progress.
1git add .
2git commit -m "feat: create layout header"Footer
Now we also want to create a footer for our layout. In our case we are just going to add some dummy social media links (again, whoever uses this template can adjust what they need). We create the same set of files we did with Header but of course we now name them Footer. The footer can be as simple as:
1import Link from 'next/link';
2import './Footer.scss';
3type FooterLink = {
4 name: string;
5 href: string;
6};
7const links: FooterLink[] = [
8 { name: 'GitHub', href: 'https://github.com/' },
9 { name: 'LinkedIn', href: 'https://www.linkedin.com/' },
10 { name: 'Email', href: 'mailto: [email protected]' },
11];
12export function Footer() {
13 return (
14 <footer className="Footer">
15 <div className="links">
16 {links.map(({ name, href }) => (
17 <Link key={name} title={name} href={href} className="FooterLink" target="_blank">
18 {name}
19 </Link>
20 ))}
21 </div>
22 </footer>
23 );
24}It is really simple, just displaying few links, but in most cases this is enough. You can easily improve it by using icons instead of text, but we won't do this in scope of this article. We want also to add a test to make sure it is all rendering as expected.
1import { render, screen } from '@testing-library/react';
2import { Footer } from './Footer';
3describe('Footer', () => {
4 it('should render properly', () => {
5 render(<Footer />);
6 const links = screen.getAllByRole('link');
7 expect(links.length).toBe(3);
8 expect(links.at(0)?.title).toBe('GitHub');
9 expect(links.at(1)?.title).toBe('LinkedIn');
10 expect(links.at(2)?.title).toBe('Email');
11 });
12});Also, we need to add exports to the index.tsx files, the same way we did with Header component.
1export { Footer } from './Footer';And use it in layout.tsx.
1import type { Metadata } from 'next';
2import { Footer, Header } from '@/components';
3import './globals.scss';
4export const metadata: Metadata = {
5 title: 'Next.js Markdown Blog',
6 description:
7 'This is a blog/portfolio website built using Nextjs 13 in which all the content is stored as markdown files.',
8};
9export default function RootLayout({
10 children,
11}: Readonly<{
12 children: React.ReactNode;
13}>) {
14 return (
15 <html lang="en">
16 <body>
17 <Header />
18 <main>{children}</main>
19 <Footer />
20 </body>
21 </html>
22 );
23}Now when it's all done we can commit the changes and start styling.
1git add .
2git commit -m "feat: create layout footer"Styling layout
Now the time comes to run our blog and apply some styles. We start the development server with yarn dev and open localhost:3000 to see our creation.
As you can see it looks... Simple. Let's stick with simple despite some other adjectives might have crossed your mind. To kick things off, let's create a layout.scss file in app and import it in the layout.tsx. We are also adding a class name of RootLayout and grid to main. The grid class will be added to globals as it will be a reusable utility class.
1import type { Metadata } from 'next';
2import { Footer, Header } from '@/components';
3import './globals.scss';
4import './layout.scss';
5export const metadata: Metadata = {
6 title: 'Next.js Markdown Blog',
7 description:
8 'This is a blog/portfolio website built using Nextjs 13 in which all the content is stored as markdown files.',
9};
10export default function RootLayout({
11 children,
12}: Readonly<{
13 children: React.ReactNode;
14}>) {
15 return (
16 <html lang="en">
17 <body>
18 <Header />
19 <main className="RootLayout grid">{children}</main>
20 <Footer />
21 </body>
22 </html>
23 );
24}Inside the layout.scss file we are going to apply some styles which will assure everything is kept in a proper space on the page.
1.RootLayout {
2 width: 100%;
3 max-width: 1200px;
4 padding: 2rem;
5 margin: auto;
6}And we also need the before mentioned grid which we add to globals.scss.
1... .grid {
2 display: grid;
3 grid-gap: 2rem;
4 grid-template-columns: 1fr;
5 align-items: start;
6}It didn't do much yet, but we can see that something is going on. We can navigate to one of the articles to maybe better see what's going on (or at least have some more content on the page). I've chosen JavaScript Best Practices: Tips and Tricks for Efficient Development. It looks better, but obviously we can see that we are missing styles for the header and footer we have created, so let's focus on those next.
Header and Footer
We can start with header. We do not need much, mostly removing the underline from the links.
1.Header {
2 width: 100%;
3 padding: 1rem;
4 display: flex;
5 justify-content: space-between;
6 background-color: var(--background-dark);
7 .logo,
8 .HeaderLink {
9 text-decoration: none;
10 color: var(--black-100);
11 }
12 .logo h1,
13 .HeaderLink {
14 &:hover,
15 &:focus {
16 color: var(--purple);
17 }
18 }
19 .logo h1 {
20 font: var(--typography-h6);
21 margin: 0;
22 }
23 .links {
24 display: flex;
25 align-content: center;
26 justify-content: flex-end;
27 .HeaderLink {
28 display: flex;
29 align-items: center;
30 margin: 0 0.25rem;
31 font: var(--typography-code);
32 &:not(:last-child):after {
33 content: '';
34 display: block;
35 width: 2px;
36 height: 1rem;
37 background-color: var(--purple);
38 margin-left: 0.5rem;
39 }
40 }
41 }
42}This gives us the following result:
This looks cool, don't you agree? We added these cool separators between navigation links and there is also a color change on hover. Now we can scroll to the bottom of the page to take care of footer.
1.Footer {
2 width: 100%;
3 padding: 1rem;
4 display: flex;
5 justify-content: center;
6 background-color: var(--background-dark);
7 .links {
8 display: flex;
9 align-content: center;
10 justify-content: flex-end;
11 .FooterLink {
12 color: var(--black-100);
13 text-decoration: none;
14 margin: 0 0.25rem;
15 &:hover,
16 &:focus {
17 color: var(--purple);
18 }
19 }
20 }
21}Saving these should immediately apply these changes to the page and the result we can see now is looking like this:
Again, this is not much, but you must admit, it does the job pretty well and is a good base for further extensions.
Adding missing globals
What will happen now, if we go back to the homepage? This doesn't look right as the footer is not sticking to the bottom. This issue is a result of some missing styling to determine the minimum height of our page's content. We can solve this by adding some global styles to body.
1... body {
2 color: var(--black-100);
3 background-color: var(--background-light);
4 display: flex;
5 flex-direction: column;
6 max-width: 100vw;
7 height: 100vh;
8}This will make sure that the content of all pages is at least one screen height and that the width is never more than the screen width. We also need to add flex-grow: 1 to layout.scss, so the layout grows to the size of the body filling the space properly.
Before we move forward it is a good time to commit the changes
1git add .
2git commit -m "feat(layout): update styling"Articles page
Some of you probably already noticed playing around that something is wrong with the articles page. Every article is there printed out as a whole, with all the content being an underlined link. Also, if you look in the browser's console you can notice some DOM validation error. This is because we are having links in our articles and these are nested in the link to the whole article - this is the cause of the error. Having the whole article content in a link also results in everything being underlined as we do not add any styles to overcome this. The amount of content of the article should just be a brief preview instead of a whole thing as well.
ArticlePreview Component
The best approach in my opinion, to solve all the above-mentioned problems is to create new variant of the Article component, which cuts the article text to just few dozens of words, removes all the links from the text and maybe look something like a card. We are going to extend our existing Article to handle some of the responsibilities, but first we need a ArticlePreview folder inside components and the set of files we used to add before. We are starting with ArticlePreview.tsx
1import Link from 'next/link';
2import { Article as TArticle } from '@/types';
3import { Article } from '@/components/Article';
4import { ARTICLES_ROUTE } from '@/constants';
5import './ArticlePreview.scss';
6type ArticleProps = {
7 article: TArticle;
8};
9const PREVIEW_WORDS = 50;
10export function ArticlePreview({ article }: ArticleProps) {
11 function getPreview(content: string): string {
12 const words = content.split(' ');
13 if (words.length > PREVIEW_WORDS) {
14 words.length = PREVIEW_WORDS;
15 }
16 return words.join(' ') + '...';
17 }
18 return (
19 <Link href={`${ARTICLES_ROUTE}/${article.slug}`} className="ArticlePreview">
20 <Article article={{ ...article, content: getPreview(article.content) }} isPreview />
21 </Link>
22 );
23}And the test for it:
1import { render, screen } from '@testing-library/react';
2import { ArticlePreview } from './ArticlePreview';
3const article = {
4 date: new Date('2000-10-10'),
5 description: 'some description',
6 content: 'some content',
7 title: 'a title',
8 topic: 'topic',
9 slug: 'slug',
10};
11describe('ArticlePreview', () => {
12 it('should render the article preview properly', () => {
13 render(<ArticlePreview article={article} />);
14 expect(screen.getByRole('link')).toHaveProperty('href', 'http://localhost/articles/slug');
15 expect(screen.getByRole('article')).toBeDefined();
16 });
17});We are taking care of cropping the content, leaving only 50 words. This component is also providing a link to the article page. You can also see we are passing isPreview parameter to the Article. This new parameter will make sure to disable some interactivity from the article, so we do not have any DOM validation errors.
1import { Article } from '@/types';
2import { Headline, DateTime, Markdown } from '@/components';
3import './Article.scss';
4type ArticleProps = {
5 article: Article;
6 isPreview?: boolean;
7};
8export function Article({ article, isPreview }: ArticleProps) {
9 const { date, description, content, title, topic } = article;
10 return (
11 <article className="Article">
12 <Headline title={title} description={description} topic={topic} />
13 <DateTime date={date} />
14 <Markdown markdown={content} isPreview={isPreview} />
15 </article>
16 );
17}In Article, we are just passing this new parameter further to Markdown, as this is the place where all text rendering is happening.
Add new powers to Markdown component
We need to now make our Markdown and based on the new parameter, simplify the rendering. To be honest the only thing we are going to handle here is replacing all the links with spans that are just going to imitate the link visually. To do so we can manipulate the components passed to ReactMArkdon (the components property can be used to replace any of the HTML components with custom ones).
1import ReactMarkdown from 'react-markdown';
2import remarkGfm from 'remark-gfm';
3import rehypeSlug from 'rehype-slug';
4import './Markdown.scss';
5import Link from 'next/link';
6import { ReactNode } from 'react';
7type MarkdownProps = {
8 markdown: string;
9 isPreview?: boolean;
10};
11export function Markdown({ markdown, isPreview }: MarkdownProps) {
12 return (
13 <ReactMarkdown
14 components={getComponents(isPreview)}
15 className="Markdown"
16 remarkPlugins={[remarkGfm]}
17 rehypePlugins={[rehypeSlug]}
18 >
19 {markdown}
20 </ReactMarkdown>
21 );
22}
23function getComponents(isPreview?: boolean) {
24 const components: Record<string, unknown> = {};
25 if (isPreview) {
26 components.a = ({ children }: { children: ReactNode }) => {
27 return <span className="a">{children}</span>;
28 };
29 } else {
30 components.a = Link;
31 }
32 return components;
33}I have added here a function getComponents which replaces the link with a span. Having a separate function just for this one component maybe is an overkill, but I know that most people (including me), will add more custom components. I think a good idea is to add some global styles to the anchor tag.
1...
2a,
3.a {
4 color: var(--purple);
5 text-decoration: none;
6}
7...Now whether it is a link or anything using the .a class, will look the same. But we can also save what we did at this point.
1git add .
2git commit -m "feat: create article preview"Updating articles page
With all the hard work we have done so far, we can finally style our articles page.
1import { ArticlePreview } from '@/components';
2import { ARTICLES_DIRECTORY } from '@/constants';
3import { FileService, MdArticleService } from '@/lib/services';
4const fileServcie = new FileService();
5const articlesService = new MdArticleService(ARTICLES_DIRECTORY, fileServcie);
6export default async function ArticlesPage() {
7 const articles = await articlesService.getAll();
8 return (
9 <div className="ArticlesPage grid">
10 <h1>Articles</h1>
11 <section className="grid">
12 {articles.map((article) => (
13 <ArticlePreview key={article.slug} article={article} />
14 ))}
15 </section>
16 </div>
17 );
18}Summary
Now go to localhost:3000/articles and admire the new, fresh and attractive look of our articles cards. We also can't see any errors in the console anymore!
And we have reached the end achieving all the goals we established at the beginning. The only missing piece here is a homepage content to have at least the minimum to call this page a functional blog. Nevertheless, there are countless ways we can make this project better like adding pagination to articles page or replacing more markdown components with custom ones. Maybe soon we will take a look at some of the possible extensions, but for now that's all! Don't forget to commit the changes, open a PR and merge it back to master. See you all soon in another article!