Open In App

template.js in Next JS

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Next.js, the template.js file can serve various purposes depending on the context and project requirements. It can be used to create reusable templates for components, pages, or even configuration settings. Utilizing a template.js file helps to maintain a consistent structure and reduce repetitive code, making your project more modular and easier to manage.

In this article, we will see about the template.js and how we can use it in our projects.

Prerequisites:

template.js in Next.js

The template file is used as a reusable component in the Next.js. This file was introduced in the app router and is similar to the layout.js file as it also wraps all the child pages or child routes and renders them to the user. The difference is that it creates a new instance of the page for each of its children while navigating, on the other hand, the "layout.js" maintains all the states defined in it. That basically means it does not maintain a state between its children and re-renders for every request and returns a new instance.

Syntax:

To create a template, you just need to create a file named "template.js" inside any of your routes/pages and export the component from it as shown below:

// inside template.js
export default function MyTemplate({children}){
// your code
return (
<>{children}</>
)
}

This is useful when you want to perform a common action whenever a user visits a page, through the "useEffect" hook as if you use the "useEffect" inside "layout.js", then it will run for the only first time (or whenever any of it's dependency changes) but in case of "template" it would run on every page. Or you might want to perform some other action on each page render which you can achieve through templates.

Steps to Create the Project

Step 1: Run the following command in your terminal to start creating your next app:

npx create-next-app@latest

Step 2: Provide the necessary details as shown below:

installation
Providing necessary details to create-next-app

Step 3: Go into the create directory and start the development server:

cd gfg-next-app
npm run dev

Folder Structure:

folder-strructure
template.js Next.js Project Structure

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.1.0"
},
"devDependencies": {
"autoprefixer": "^10.0.1",
"postcss": "^8",
"tailwindcss": "^3.3.0",
"eslint": "^8",
"eslint-config-next": "14.1.0"
}

Example 1: Let us create two pages namely home page and contact page and share a common template throughout them by the "template.js".

JavaScript
// src/app/template.js

import Link from "next/link";
export default function RootTemplate({ children }) {
	return (
		<div className="p-5">
			<nav className="mb-4">
				<h1 id="logo" className="text-2xl font-bold text-green-600">
					GeeksforGeeks
				</h1>
				<h3 className="text-lg font-bold">template.js | Next.js</h3>
				<Link href="/" className="text-sm underline block">
					Home
				</Link>
				<Link href="/contact" className="text-sm underline block">
					Contact
				</Link>
			</nav>
			{children}
		</div>
	);
}
JavaScript
// inside src/app/page.js

export default function Home() {
	return <p className="font-bold">I am homepage.</p>;
}
JavaScript
// inside src/app/contact/page.js

export default function Contact() {
	return <p className="font-bold">I am contactpage.</p>;
}

Output:

Example 2: In this example, let's add the code so that whenever user changes the page from home page to the about page, the background color of the page changes randomly between the specified colors. For this, we would need to make the "template.js" as a client component so as to use the react hooks in it.

JavaScript
// src/app/template.js

"use client";
import { useEffect } from "react";
import Link from "next/link";
export default function RootTemplate({ children }) {
	useEffect(() => {
		const colors = ["#FFE4E1", "#ADD8E6", "#90EE90"];
		const randomColor = colors[Math.floor(Math.random() * colors.length)];
		document.body.style.backgroundColor = randomColor;
	}, []);
	return (
		<div className="p-5">
			<nav className="mb-4">
				<h1 id="logo" className="text-2xl font-bold text-green-600">
					GeeksforGeeks
				</h1>
				<h3 className="text-lg font-bold">template.js | Next.js</h3>
				<Link href="/" className="text-sm underline block">
					Home
				</Link>
				<Link href="/about" className="text-sm underline block">
					About
				</Link>
			</nav>
			{children}
		</div>
	);
}
JavaScript
// src/app/about/page.js

export default function AboutPage() {
	return <p className="font-bold">I am aboutpage.</p>;
}
JavaScript
// src/app/about/page.js

export default function AboutPage() {
    return <p className="font-bold">I am aboutpage.</p>;
}

Output:

Conclusion

The template.js file in Next.js is a powerful tool for creating reusable components, page layouts, and configuration settings. By leveraging templates, you can enhance the consistency, reusability, and maintainability of your application. Adhering to best practices ensures that your templates remain modular, flexible, and well-documented, contributing to a more efficient and scalable codebase.


Next Article

Similar Reads