Layouts in Next.js allow you to create reusable structures that can be shared across multiple pages. This ensures a consistent look and feel throughout your application while reducing code duplication. Next.js 13 introduced enhanced layout capabilities, allowing for nested and dynamic layouts. In this article, we will see Next.js Layouts.
Prerequisites:
What are Layouts in Next.js?
Layouts in Next.js is a higher-order component (HOC) that wraps your application's pages. It allows you to define a consistent structure and appearance for all your pages, making it easy to maintain a consistent user experience. Layouts are a great way to reuse code and save time, especially when building larger applications.
Syntax:
const Layout = ({ children }) => {
return (
<div>
<header>Your header</header>
<main>{children}</main>
<footer>Your footer</footer>
</div>
)
}
Global Layouts:
Define a layout that wraps your entire application. This is typically used for elements like headers, footers, and navigation bars that appear on every page.
The global layout wraps the complete application and for which it is use in _app.js file.
// pages/_app.js
import Layout from '../components/layout'
function MyApp({ children, Component }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
export default MyApp;
Nested Layouts:
Create layouts that are specific to certain sections of your application. For example, an admin dashboard may have a different layout from the public-facing pages.
// app/dashboard/layout.js
export default function DashboardLayout({ children }) {
return (
<div className="dashboard-layout">
<aside>Dashboard Sidebar</aside>
<main>{children}</main>
</div>
);
}
// app/dashboard/page.js
export default function DashboardPage() {
return <h1>Dashboard Home</h1>;
}
Dynamic Layouts:
Adjust layouts dynamically based on the context or route parameters. This is useful for changing the layout based on user roles or specific page requirements.
export default function RoleBasedLayout({ children, params }) {
return (
<div className={`layout-${params.role}`}>
<header>{params.role} Header</header>
<main>{children}</main>
</div>
);
}
// app/[role]/page.js
export default function RolePage({ params }) {
return <h1>{params.role} Page</h1>;
}
Steps to Create a Next.js Layout
Step 1: First, we need to create a new file in our components folder and name it like "Layout.js"
JavaScript
// Filename - components/Layout.js
import React from 'react'
const Layout = ({ children }) => {
return (
<div>
<header>Navbar</header>
<main>{children}</main>
<footer>Footer</footer>
</div>
)
}
export default Layout;
In this file, we have defined our layout component which consists of a header, a main section, and a footer. The children's prop is used to pass in the content of the page being wrapped by the layout.
Step 2: Single Shared Layout with Custom App
Setting the layout in a single page:
After creating a layout component, it is now available to use on the pages. To do that we can import it and wrap it in a page component with it. For example, if we have a page called "About.js", we can wrap it with the layout below:
JavaScript
//pages/About.js
import React from 'react'
import Layout from '../components/Layout'
const About = () => {
return (
<Layout>
<h1>About page</h1>
<p>This is the about page content.</p>
</Layout>
)
}
export default About
In the above code, the About page component is wrapped with the Layout component. The content of the page is passed to the layout component via the children's prop.
Setting the default layout for all pages:
To use the layout as global layout just wrap all the component in _app.js with the required layout.
JavaScript
// pages/_app.js
import Layout from '../components/layout'
function MyApp({ children, Component }) {
return (
<Layout>
<Component {...pageProps} />
</Layout>
);
}
export default MyApp;
In the above code, the MyApp component is used as a wrapper for all pages in the application. The Component prop represents the current page being rendered, and the pageProps prop contains any initial props passed to the page.
Example: Below example demonstrates how to implement global layout.
In the below example, we have created a layout component in the layout.js file. After creating it, we exported the component to use it on other pages. In the _app.js file inside the pages folder, we have added our layout component by importing it and wrapped the layout component in the About.js component.
JavaScript
//pages/_app.js
import "../styles/globals.css";
import Layout from '../components/layout'
import About from "./About";
function MyApp({ Component, pageProps }) {
return (
<Layout>
<About />
</Layout>
);
}
export default MyApp;
JavaScript
//pages/About.js
import React from 'react'
function About() {
return (
<div style={{ textAlign: 'center' }}>
<h1>Welcome to GeeksforGeeks About Page</h1>
</div>
)
}
export default About
JavaScript
//components/layout.js
import React from 'react'
const Layout = ({ children }) => {
return (
<div>
<header style={{
backgroundColor: 'green',
color: 'white',
padding: 10
}}>
Navbar
</header>
<main>{children}</main>
<footer style={{
backgroundColor: 'black',
color: 'white',
padding: 10,
position: 'fixed',
bottom: 0,
width: '100%'
}}>
Footer
</footer>
</div>
)
}
export default Layout;
Step to run:
Step 1: Run the following command in your project directory:
npm run dev
Step 2: Go to localhost:portnumber
localhost:3000
Output:
NextJS LayoutsBenefits of using layouts in Next.js
Layouts can be very beneficial for all of us while building any web application. Below are some of the benefits that Next.js provide in Layouts:
- Consistency: Using a layout in your application, ensures that all pages in your application have a consistent structure and appearance. which makes it easier for the users to navigate your application easily and understand its purpose.
- Reusability: Layouts help in reusing code and saving time when building larger applications. If you have created a single layout component and have used it across multiple pages, you can avoid duplicating code and may reduce the risk of errors.
- Scalability: As your application grows, layouts make it easier to manage the structure and appearance of your pages. By defining a layout, you can quickly update the structure and appearance of all pages in your application.
Conclusion
Layouts in Next.js offer a powerful way to maintain a consistent design across your application while enabling flexibility through nested and dynamic layouts. By leveraging these features, you can create a well-structured, maintainable, and scalable application with a cohesive user experience. Following best practices for modularity, styling, performance, and error handling will help you maximize the benefits of using layouts in Next.js.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. Why Use React?Before React, web development faced issues like slow DOM updates and mes
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Stateless (before hooks)
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects