
Creating Article component
It's time to start making our blog look nice
Introduction
In the previous article (Setting up unit testing), we focused on setting up Jest and React Testing Library to handle unit tests in our application. I did that so early, almost at the beginning of the whole course, because I want to make sure we can write tests for everything we build. This way we won't create a backlog of tests to be added somewhere in the future when we finally have the testing environment up and running. So, today we can finally start building the UI components which we will later use throughout our whole blog. We are going to look at CSS variables to provide consistent styling. I am also creating a new branch to work on this feature. I called mine add-article-component but you can name it the way you want.
Defining global styles
As mentioned above, we are going to use CSS variables to store some global parameters like fonts and colors which we are going to use anywhere. This is going to prevent us from having any inconsistencies in the page's visuals, but also it will enable us to easily manipulate these variables to change the look of our whole website from one, central place To store the global styling we are going to update the globals.scss file we have in our project in src/app directory.
1@import url('https://fonts.googleapis.com/css2?family=PT+Mono&family=Roboto&family=Ubuntu+Mono&display=swap');
2:root {
3 --black-100: #1d1f23;
4 --black-90: #21252b;
5 --black-80: #333333;
6 --black-70: #4d4d4d;
7 --black-60: #666666;
8 --black-50: #808080;
9 --black-40: #9aa2b1;
10 --black-30: #abb2bf;
11 --black-20: #cccccc;
12 --black-10: #e6e6e6;
13 --black-0: #ffffff;
14 --background-light: #ffffff;
15 --background-dark: #f3f3f3;
16 --purple: #b06bc4;
17 --red: #c76068;
18 --green: #79a858;
19 --blue: #579dd6;
20 --yellow: #ccab6e;
21 --gray: #d3d3d3;
22 --typography-h1: 2.5em 'Roboto';
23 --typography-h2: 2.25em 'Roboto';
24 --typography-h3: 2em 'Roboto';
25 --typography-h4: 1.75em 'Roboto';
26 --typography-h5: 1.5em 'Roboto';
27 --typography-h6: 1.25em 'Roboto';
28 --typography-p: 1em 'Ubuntu', sans-serif;
29 --typography-code: 1em 'PT Mono', sans-serif;
30}
31*,
32*::before,
33*::after {
34 margin: 0;
35 padding: 0;
36 box-sizing: border-box;
37 min-width: 0;
38}
39html {
40 font-size: 16px;
41 scroll-behavior: smooth;
42 font: var(--typography-p);
43}
44h1,
45h2,
46h3,
47h4,
48h5,
49h6 {
50 color: var(--black-100);
51 line-height: 1.5;
52 margin-top: 1em;
53 margin-bottom: 0.75em;
54}
55h1 {
56 font: var(--typography-h1);
57}
58h2 {
59 font: var(--typography-h2);
60}
61h3 {
62 font: var(--typography-h3);
63}
64h4 {
65 font: var(--typography-h4);
66}
67h5 {
68 font: var(--typography-h5);
69}
70h6 {
71 font: var(--typography-h6);
72}
73p,
74ul,
75ol {
76 color: var(--black-80);
77 line-height: 1.5;
78}Let's analyze what we've got here. We start by importing some google fonts we are going to use. All the headings are going to be Roboto, text Ubuntu and code PT Mono. Of course, you can change them to anything you like. Then we declare the variables. In CSS to declare global variables you have to put them inside :root selector. We are declaring a range of colors, different shades of gray and typography as well. Underneath the :root we assign some global styling to headers, paragraphs and so on.
Creating an article component
This is the core functionality of our page, to display the article written in Markdown on our page. To do so we are going to build Artcile component. This component will not be all stored in single file. It will be built from number of smaller component, each of which will do just one part of the job like formatting the creation date or title and description.
Article component bare bones
We are going to start by building an Artciel component. For now, it is not really going to do anything spectacular by itself, but we will make a structure of all the pieces we are going to need to make the final, working product. All the components we are going to share in more than one page we are going to store in src/components directory. Let's create Article folder inside components and 4 files inside - Article.tsx, Article.test.tsx, Article.scss and index.tsx.
1import { Article } from '@/types';
2import './Article.scss';
3type ArticleProps = {
4 article: Article;
5};
6export function Article({ article }: ArticleProps) {
7 return (
8 <article className="Article">
9 <Headline />
10 <DateTime />
11 <Markdown />
12 </article>
13 );
14}1export { Article } from './Article';This of course underlines all the components we do not currently have, but we now know what we need. So. basically I decided to have 3 separate subcomponents which are together building the Article:
- Headline - displays title and description
- Date - display article's creation date
- Markdown - renders markdown content All the styling files we are going to just create and leave empty for now. We will revisit them later, when we finish all the components and make the
Articlework. Then, when we import it on our articles page, we are going to run the development server and play with the styling. This way we will have a live preview of the results we are getting.
Headline Component
Now we create Headline directory in components. Inside we add 4 new files: Headline.tsx, Headline.test.tsx, Headline.scss and `index.tsx. We create the
1import './Headline.scss';
2type HeadlineProps = {
3 title: string;
4 description: string;
5 topic?: string;
6};
7export function Headline({ description, title, topic }: HeadlineProps) {
8 return (
9 <div className="Headline">
10 {topic && <p className="topic">Topic: {topic}</p>}
11 <h1>{title}</h1>
12 <p className="description">{description}</p>
13 </div>
14 );
15}1export { Headline } from './Headline';It is super simple and what it does is just rendering the title and description. Now we can also add some tests. To do so we update the Healine.test.tsx.
1import { render, screen } from '@testing-library/react';
2import { Headline } from './Headline';
3describe('Headline', () => {
4 it('should render the article headline properly', () => {
5 render(<Headline topic="topic" description="some description" title="a title" />);
6 expect(screen.getByRole('heading').textContent).toEqual('a title');
7 expect(screen.getByText('some description')).toBeDefined();
8 expect(screen.getByText('Topic: topic')).toBeDefined();
9 });
10});Such a simple component doesn't need more than this one test which is just checking if what we pass to it is rendered.
DateTime Component
Same as before we need new folder and the same set of files as before. The DateTime component is as simple as taking the date and displaying it as a locale string.
1import './DateTime.scss';
2type DateTimeProps = {
3 date: Date;
4};
5export function DateTime({ date }: DateTimeProps) {
6 return <time className="DateTime">{date.toLocaleString()}</time>;
7}1export { DateTime } from './DateTime';We can also add a test to make sure it works as expected.
1import { render } from '@testing-library/react';
2import { DateTime } from './DateTime';
3describe('DateTime', () => {
4 it('should render properly', () => {
5 const date = new Date('2000-10-10');
6 const { container } = render(<DateTime date={date} />);
7 expect(container.textContent).toBe('10/10/2000, 2:00:00 AM');
8 });
9});Markdown Component
This is the most complex one and it also needs some external dependencies. We are going to use react-markdown package, together with some rehype and remark plugins. Let's start by installing dependencies.
1yarn add react-markdown remark-gfm rehype-slugNext, as before we add a new folder Markdown inside components and we also create the same files as we did for any of the previous components. This is how our main Markdown.tsx looks like:
1import ReactMarkdown from 'react-markdown';
2import remarkGfm from 'remark-gfm';
3import rehypeSlug from 'rehype-slug';
4import './Markdown.scss';
5type MarkdownProps = {
6 markdown: string;
7};
8export function Markdown({ markdown }: MarkdownProps) {
9 return (
10 <ReactMarkdown className="MarkDown" remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeSlug]}>
11 {markdown}
12 </ReactMarkdown>
13 );
14}1export { Markdown } from './Markdown';This component takes as a prop just the markdown content it will be rendering. We are also using remark-gfm plugin which can handle rendering of some additional markdown extensions like tables, task lists and so on. More about this plugin you can find in the docs. We are also using the rehype-slug plugin to add IDs to each header element in the text. This might be useful to share with someone link to not only the whole article, but to a specific section within by referencing the header ID in the URL like so our-blog.com/articles/this-is-an-article#header-id. For this one I'm not going to write tests because I would have to mock the react-markdown and the two other plugins, so it does not really make sense. We also need to export all the components in components/index.tsx to be able to import it later in Article.
1export { Article } from './Article';
2export { DateTime } from './DateTime';
3export { Headline } from './Headline';
4export { Markdown } from './Markdown';Updating Article
Now when we have all the pieces we can import them and use in the Article component.
1import { Article } from '@/types';
2import { Headline, DateTime, Markdown } from '@/components';
3import './Article.scss';
4type ArticleProps = {
5 article: Article;
6};
7export function Article({ article }: ArticleProps) {
8 const { date, description, content, title, topic } = article;
9 return (
10 <article className="Article">
11 <Headline title={title} description={description} topic={topic} />
12 <DateTime date={date} />
13 <Markdown markdown={content} />
14 </article>
15 );
16}This looks good. Let's test it and see if it works as expected. An example of a test that can check our Article can look like so:
1import { render, screen } from '@testing-library/react';
2import { Article } from './Article';
3describe('Article', () => {
4 it('should render the article properly', () => {
5 const article = {
6 date: new Date('2000-10-10'),
7 description: 'some description',
8 content: 'some content',
9 title: 'a title',
10 topic: 'topic',
11 slug: 'a-title',
12 };
13 render(<Article article={article} />);
14 expect(screen.getByRole('heading').textContent).toEqual('a title');
15 expect(screen.getByText('some description')).toBeDefined();
16 expect(screen.getByText('Topic: topic')).toBeDefined();
17 expect(screen.getByText('10/10/2000, 2:00:00 AM')).toBeDefined();
18 expect(screen.getByText('some content')).toBeDefined();
19 });
20});Mocks
But if we run this test with yarn test:watch, we will start to get errors with some export problems. Pretty cryptic and actually not really helpful message. But what is this all about? Well, as I mentioned before explaining the reason why I am not going to write tests for Markdown component? I mention it does not make sens e to mock all the libraries. Why would we have to do this? It's because these libraries are not working properly with our testing setup. So in case of the Markdown component we just didn't write a test, but this time we want to add mocks to be able to test any other component that renders Markdown. To do so we have to create a src/__mocks__ folder (make sure you are using double underscores on bots sides). Inside we are going to add files that will be used as mocks for our libraries of choice. Every file has to have a name of the library so in our case we create three files: react-markdown.js, remark-gfm.js and rehype-slug.js. That's how I mocked them to make them work with the test we have.
1export default function ReactMarkdown({ children }) {
2 return <>{children}</>;
3}1export default jest.fn();1export default jest.fn();The last two we just mock with a jest.fn() as they are just a plugins passed to the function we are mocking up anyway in react-markdown.js. The react-markdown simply renders its children, so we can test that the content we are passing is displayed. We also need to include mocks in TypeScript config. To do so we have to edit our tsconfig.json file by adding "src/__mocks__/*.js" to the includes array. Now when we run the tests again, they all pass.
Using Article component on articles page
Now we can finally use our new component on the page and start making it look good. First we need to update the [slug]/page.tsx to use our component.
1import { Article } from '@/components';
2import { ARTICLES_DIRECTORY } from '@/constants';
3import { FileService, MdArticleService } from '@/lib/services';
4import './ArticlePage.scss';
5const fileServcie = new FileService();
6const articleService = new MdArticleService(ARTICLES_DIRECTORY, fileServcie);
7export async function generateStaticParams() {
8 const articles = await articleService.getAll();
9 return articles.map((article) => ({ slug: article.slug }));
10}
11export const dynamicParams = false;
12type AtricleProps = { params: { slug: string } };
13export default async function ArticlePage({ params: { slug } }: AtricleProps) {
14 const article = await articleService.getOneBySlug(slug);
15 return (
16 <section className="ArticlePage">
17 <Article article={article} />
18 </section>
19 );
20}Make sure to also create ArticlePage.scss file in the [slug] directory as we are importing it here and we will use it to style the page later. Now we can run yarn dev open one of our articles http://localhost:3000/articles/javascript-mastering-javascript-a-comprehensive-guide and we can see it is still working. We can also see it does render markdown properly! I think this is a proper time to save our progress
1git add .
2git commit -m "feat: create article component"Styling Article
So now with the development server running. We can start to add some styles to the Article component. We are going to do all the changes in Article.scss
Right now our page doesn't look impressive, but we are going to change it.
We just have to add some styling to DateTime.scss and Markdown.scss first.
1.DateTime {
2 display: inline-block;
3}1.Markdown {
2 code,
3 pre {
4 word-wrap: break-word;
5 white-space: pre-wrap;
6 }
7}The first one just makes sure that the time element we used there is treated as a block element, so we can add for example margins to it. The second one allows code blocks to wrap their text if its longer then the screen width, preventing horizontal scrollbar.
1.Article {
2 padding: 1rem;
3 .topic {
4 font-size: 1.2rem;
5 color: var(--black-60);
6 }
7 .description {
8 font-size: 2rem;
9 color: var(--purple);
10 text-align: right;
11 }
12 .DateTime {
13 margin-top: 1rem;
14 font-size: 0.875rem;
15 color: var(--black-60);
16 }
17}Here we add some more specific styling to each of the subcomponents and to the Article itself. It's not much, but it already looks a lot better.
Summary
Next we have to style the page, and improve the layout in general. However, this is a perfect spot to finish this part. We can save our progress, create a PR an merge it. In the next article where we are going to continue making our blog glow. I hope to see you all in Building layout and styling pages!