0
0
RemixHow-ToBeginner ยท 4 min read

How to Create Dynamic Routes in Remix Framework

In Remix, create a dynamic route by adding square brackets around the parameter name in the route file, like app/routes/$param.jsx. This lets Remix capture that part of the URL as a variable you can use in your component via useParams().
๐Ÿ“

Syntax

Dynamic routes in Remix use file names with square brackets to capture URL segments as parameters. For example, $id.jsx captures the id part of the URL.

  • $param: The name inside brackets becomes the parameter key.
  • File location: Placed inside app/routes/ folder to define the route.
  • Use useParams() hook inside the component to access the parameter value.
jsx
app/routes/$id.jsx

import { useParams } from '@remix-run/react';

export default function Item() {
  const params = useParams();
  return <div>Item ID: {params.id}</div>;
}
๐Ÿ’ป

Example

This example shows a dynamic route that captures a user ID from the URL and displays it on the page.

jsx
app/routes/users/$userId.jsx

import { useParams } from '@remix-run/react';

export default function UserProfile() {
  const { userId } = useParams();
  return (
    <main>
      <h1>User Profile</h1>
      <p>User ID: {userId}</p>
    </main>
  );
}
Output
If you visit /users/123, the page shows: User Profile User ID: 123
โš ๏ธ

Common Pitfalls

  • Forgetting to wrap the parameter name in square brackets causes Remix to treat it as a static route.
  • Not using useParams() inside the component means you can't access the dynamic value.
  • Using the wrong parameter name in useParams() will result in undefined.
  • Dynamic routes must be placed inside app/routes/ folder to work.
jsx
/* Wrong: static route file name */
app/routes/userId.jsx

/* Right: dynamic route file name */
app/routes/$userId.jsx

/* Wrong: accessing wrong param */
const { id } = useParams(); // but file is $userId.jsx

/* Right: matching param name */
const { userId } = useParams();
๐Ÿ“Š

Quick Reference

ConceptDescriptionExample
Dynamic route fileFile name with parameter in brackets$postId.jsx
Parameter accessUse useParams() hook inside componentconst { postId } = useParams();
Route URLMatches URL segment for parameter/posts/42
Static routeFile name without bracketsabout.jsx
Folder locationPlace route files inside app/routes/app/routes/$param.jsx
โœ…

Key Takeaways

Create dynamic routes by naming files with square brackets around the parameter, like $id.jsx.
Access the dynamic part of the URL inside your component using the useParams() hook.
Ensure the parameter name in useParams() matches the file name exactly.
Place dynamic route files inside the app/routes/ folder for Remix to recognize them.
Avoid naming files without brackets if you want dynamic behavior.