CORE CONCEPTS
Dynamic Routes
Dynamic Routes
are routes that are generated at runtime. This is useful when you have a large number of pages that are similar, but not exactly the same.
For example, you might want to create a page for each user on your website. Instead of creating a page for each user, you can create a single page that uses a dynamic route to load the user's data.
Here is an example of a Dynamic Route
to display a user's profile page.
tsximport { PageComponent } from "rasengan"; const Profile: PageComponent = () => { return ( <div> <h1>User Profile</h1> </div> ) } Profile.path = "/profile/:id"; Profile.metadata = { title: "Profile", description: "User Profile", } export default Profile;
In the example above, we have created a Dynamic Route
to display a user's profile page.
The :id
in the route path is a dynamic parameter that can be used to load the user's data based on his userId
.
To access the dynamic route parameters, you can use the useParams
hook.
tsximport { PageComponent, useParams } from "rasengan"; const Profile: PageComponent = () => { const { id } = useParams(); return ( <div> <h1>User Profile</h1> <p>User ID: {id}</p> </div> ) } Profile.path = "/profile/:id"; Profile.metadata = { title: "Profile", description: "User Profile", } export default Profile;
You can also create a Dynamic Route
with optional parameters.
tsximport { PageComponent, useParams } from "rasengan"; const Profile: PageComponent = () => { const { id } = useParams(); console.log(id) // id can be undefined return ( <div> <h1>User Profile</h1> </div> ) } Profile.path = "/profile/:id?"; Profile.metadata = { title: "Profile", description: "User Profile", } export default Profile;
In the example above, we have created a Dynamic Route
with an optional parameter. The ?
at the end of the route parameter makes it optional.
By doing like this, when we access the /profile
route, the id
will be undefined
and we won't get a 404 error
. But in the case where the id
is not optional
,
navigating to /profile
will result in a 404 error
.
You can have optional static segments
too.
tsProfile.path = "/profile/:id?/edit?";
You can also create a Dynamic Route
with multiple parameters.
tsximport { PageComponent, useParams } from "rasengan"; const Profile: PageComponent = () => { const { id, name } = useParams(); console.log(id, name) // id and name can be undefined return ( <div> <h1>User Profile</h1> </div> ) } Profile.path = "/profile/:id?/:name?"; Profile.metadata = { title: "Profile", description: "User Profile", } export default Profile;
You can chain multiple parameters in a Dynamic Route
by separating them with a /
.