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 inundefined. - 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
| Concept | Description | Example |
|---|---|---|
| Dynamic route file | File name with parameter in brackets | $postId.jsx |
| Parameter access | Use useParams() hook inside component | const { postId } = useParams(); |
| Route URL | Matches URL segment for parameter | /posts/42 |
| Static route | File name without brackets | about.jsx |
| Folder location | Place 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.