Parallel Routing in NextJS
In NextJS, it is possible to make a part of the site display different content depending on the requested URL. This is called parallel routing.
Let's look at an example. Suppose we have the following site layout:
export default function RootLayout({children}) {
return (
<html lang="en">
<body>
<header>
header
</header>
<main>
{children}
</main>
<footer>
footer
</footer>
</body>
</html>
);
}
Let's say we want the header
to display dynamic information.
Let the URL /users display
a component with users, and the URL
/posts display a component with posts.
For such parallel routing,
you need to create a special folder,
starting its name with the symbol @.
For example, let's name our folder @info.
In this folder, we will place two components.
The first one for displaying users in the folder /users/,
and the second one for displaying posts in the folder /posts/.
We will get the following file structure:
- /app/
- /@info/
- /users/
- page.jsx
- /posts/
- page.jsx
- /users/
- /@info/
Now we need to write a special command for insertion in the site layout. For this, we need to use a special dynamic slot.
To understand what it is, first look at the parameter of our site layout function:
export default function RootLayout({children}) {
return (
);
}
Pay attention to the fact that
an object is passed as a parameter,
from which we extract the site content into the variable
children.
There can be other keys in this object.
They correspond to those folders whose names
start with @.
In our case, we have the folder @info,
which means we will have access to the
variable info, which, depending
on the URL, contains the text of one of
the components - users or posts.
Let's get this variable:
export default function RootLayout({children, info}) {
return (
);
}
Now inside the layout markup, we can
output the variable info.
Depending on the URL, the text of one of our components
will be inserted into this place:
export default function RootLayout({children, info}) {
return (
<html lang="en">
<body>
<header>
<div>
{info}
</div>
</header>
<main>
{children}
</main>
<footer>
footer
</footer>
</body>
</html>
);
}
Create a dynamic slot for the right sidebar.
Create a dynamic slot for the left sidebar.