Routing Fundamentals
The skeleton of every application is routing. This page will introduce you to the fundamental concepts of routing for the web and how to handle routing with another-react-router.
Note: Main content of routing is based on NEXT.js documentation site. Read more why.
Terminology
First, you will see these terms being used throughout the documentation. Here's a quick reference:
- Tree: A convention for visualizing a hierarchical structure. For example, a component tree with parent and children components, a folder structure, etc.
- Subtree: Part of a tree, starting at a new root (first) and ending at the leaves (last).
- Root: The first node in a tree or subtree, such as a root layout.
- Leaf: Nodes in a subtree that have no children, such as the last segment in a URL path.
- URL Segment: Part of the URL path delimited by slashes.
- URL Path: Part of the URL that comes after the domain (composed of segments).
Roles of Folders and Files
Another react router uses a file-system based router where:
- Folders are used to define routes. A route is a single path of nested folders, following the file-system hierarchy from the root folder down to a final leaf folder that includes a
page.(js/ts/jsx/tsx)
file. See Defining Routes. - Files are used to create UI that is shown for a route segment. See special files.
Route Segments
Each folder in a route represents a route segment. Each route segment is mapped to a corresponding segment in a URL path.
Nested Routes
To create a nested route, you can nest folders inside each other. For example, you can add a new /dashboard/settings
route by nesting two new folders in the routes directory
.
The /dashboard/settings route is composed of three segments:
/
(Root segment)dashboard
(Segment)settings
(Leaf segment)
File Conventions
Next.js provides a set of special files to create UI with specific behavior in nested routes:
layout | Shared UI for a segment and its children |
page | Unique UI of a route and make routes publicly accessible |
not-found | Not found UI for a segment and its children |
Good to know:
.js
,.jsx
,.ts
or.tsx
file extensions can be used for special files.
Component Hierarchy
The React components defined in special files of a route segment are rendered in a specific hierarchy:
layout.js
not-found.js
(React error boundary)page.js
or nestedlayout.js
In a nested route, the components of a segment will be nested inside the components of its parent segment.
Colocation
In addition to special files, you have the option to colocate your own files (e.g. components, styles, tests, etc) inside folders in the app
directory.
This is because while folders define routes, only the contents returned by page.js
or route.js
are publicly addressable.
Learn more about Project Organization and Colocation.
Next Steps
Now that you understand the fundamentals of routing in another react router, follow up on the navigation sidebar.