Next.js Blog Tutorial - Part 3
Learn how to pass data as props and refactor duplicate code into DRY code.
Starting Code: https://replit.com/@buckldav/next-tut-2.
Don’t Repeat Yourself (DRY)
When we created our blog posts, we copied and pasted the entire structure from one post to another. This is hard to maintain because if we wanted to change how a post was structured, we would have to change every file. DRY is a programming principle to create maintainable code. In our case, we will define our blog posts’ structure once in as a Blog component and then reuse that component for each post page.
Components with Data - Blog Component
When creating a component, you can pass a parameter into the function known as props
.
export default function Component(props) {}
props
can contain data related to your component. The data is accessed with the .
operator. Make a new file at components/Blog.js
and add the following code (you can also copy + paste post1.js
and modify it). Notice the props we will require.
components/Blog.js
import Head from "next/head"
export default function Blog(props) {
return (
<main>
<Head>
<title>My Next App | {props.title}</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<article>
<header>
<h1>{props.title}</h1>
<p>{props.date}</p>
<p>by {props.author}</p>
</header>
<div>{props.children}</div>
</article>
</main>
)
}
Now, in pages/blog/post1.js
, we can use this Blog component and pass props as attributes in its tag.
// pages/blog/post1.js
import Blog from "../../components/Blog"
export default function Post1() {
return (
<Blog author="David Buckley" date="October 14, 2021" title="Post 1">
{/* Content between the tags becomes "props.children" in the component */}
<p>This is some content for my first post.</p>
</Blog>
)
}
Do the same for post2.js
.
Summary
We created a Blog component and used props to pass the unique data for each post into the component.
Finished code: https://replit.com/@buckldav/next-tut-3.