Linking and Navigating
There are two ways to navigate between routes in Rasengan.js:
- Using the
<Link>
Component - Using the
useNavigate
hook
This page will go through how to use each of these options, and dive deeper into how navigation works.
Using the <Link>
Component
The <Link>
component is a React component that allows you to navigate between routes in your application.
It is the recommended way to navigate between routes in Rasengan.js.
Here's an example of how to use the <Link>
component:
To handle Routing
in Rasengan.js, we have based our routing on the
react-router
library. So, you can learn more about the Link Component
(opens in a new tab) from the
react-router
documentation.
There are other option props available to <Link />
, see the API Reference
for more details.
Examples
Using dynamic routes
You can use the to
prop to navigate to a dynamic route. For example, if you have a route with a dynamic parameter, you can pass the parameter to the to
prop.
import { Link } from "rasengan";
type Props = {
posts: {
id: number;
title: string;
}[];
};
export default function PostList({ posts }: Props) {
return (
<div>
{posts.map((post) => (
<div key={post.id}>
<h2>{post.title}</h2>
<Link to={`/post/${post.id}`}>Read More</Link>
</div>
))}
</div>
);
};
Checking active links
You can use the useLocation
hook to have access to the current pathname
of the URL and use it to check if the link is active.
import React from "react";
import { Link, useLocation } from "rasengan";
type Props = {
to: string;
children: React.ReactNode;
};
export default function ActiveLink({ to, children }: Props) {
const { pathname } = useLocation();
return (
<Link to={to} className={`link ${pathname === to ? "active" : ""}`}>
{children}
</Link>
);
}
Scrolling to an id
The default behavior of a Rasengan.js Routing system is to navigate to the top of the page when a new route is visited.
If you want to scroll to a specific id
on the page, you can use the to
prop with the hash
value.
useNavigate
hook
The useNavigate
hook is used to change the current route in your application.
It returns a function that you can call to navigate to a different route.
Here's an example of how to use the useNavigate
hook:
For a full list of useNavigate
options, see the API reference (opens in a new tab) on the documentation of React Router
.
useNavigate
is useful when you want to do something before navigating to the
new page.