Shared components in Next.js

Today we will show you how to create shared components in Next.js. With the help of shared components, we can reduce the logic of the application and organize the work together.

Shared components between pages, How to create common component in Next.js, Persistent Layout Patterns in Next.js, Build website in Next.js, Sharing component in Next.js with Custom application, Getting start with Next.js Framework for server-rendered React application.

We will continue with the previous Next.js article and optimize the pages with the help of higher order components.

Steps to implement shared components

  1. Setup Next.js application
  2. Create shared component
  3. Import shared component in pages
  4. Output

1. Setup Next.js application

In order to setup Next.js application, please follow the link below for your reference.

How to setup a project in Next.js

We will continue with the previous article and create the Layout component and share it with pages.

2. Create shared component

To create a shared component, First you have to create a components folder in the root directory. Now let’s create a Layout component in components directory.

We should have Header, Footer, Title and basic structure in the Layout component. Following code will help you to create it.

components/Layout.js

3. Import shared component in pages

We have successfully created the shared component and now it’s time to import it in pages. We need to import it the same as the other files in the pages. We will also pass the title as props in the shared component.

I have updated the changes in each file. Refer below code for your understanding.

pages/index.js

pages/about.js

pages/contact.js

4. Output

Only that’s the changes required for the shared components. You may modify the component or create more components based on your needs. Output should remain the same as the previous article.

Output - Shared components in Next.js - Clue Mediator
Output – Shared components in Next.js – Clue Mediator

Thank you for reading. Happy Coding!

Demo & Source Code

Github Repository

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *