Navigate between pages
In this tutorial, we'll explore how to navigate between two pages within the MagicJS framework and utilize route parameters for dynamic page rendering.
Setting Up Pages
Create two UI files named
page1.tsxandpage2.tsx, with corresponding paths '/page-1' and '/page-2' respectively.Update the content in each page for better understanding.
For example:
import React from "react"
export default function Component(props: any) {
return <div>Hello World from page 1</div>
}Navigating Between Pages
Refer the below snippet.
import { Link } from "@magicjs.dev/frontend"
import React from "react"
import { Button } from "antd"
export default function Component(props: any) {
return (
<div>
Hello World from page 1
<Link to="/page-2">
<Button>Go to page 2</Button>
</Link>
</div>
)
}In
page1.tsx, import theLinkcomponent frommagicjs.dev/frontend.Create a button inside the
Linkcomponent, utilizing the AntDButton.Set the
toprop in theLinkcomponent to"/page-2".After refreshing the page, you'll see the button. Clicking on it will navigate to page 2.
Now, Repeat these steps on the other page to establish bidirectional navigation between them.
Utilizing Route Parameters
Next, let's explore how to add route parameters to page 2, such as :productId.
In
app.jsonfile, add/:productIdto the path of page 2 and save.
Refer the snippet given below.
{
"path": "/page-2/:productId",
"view": "features/main-features/page2.tsx"
}In
page2.tsx, utilize theuseRoutehook to access routing information and store its value in a variable namedrouteand update the content to render theproductIdobtained from the route.
Refer the code given below.
import { Link, useRoute } from "@magicjs.dev/frontend"
import React from "react"
import { Button } from "antd"
export default function Component(props: any) {
const route = useRoute()
return (
<div>
{`Page for product: ${route?.match?.productId}`}
<Link to="/page-1">
<Button>Go to page 1</Button>
</Link>
</div>
)
}Update the link in page 1 to include a specific product ID, e.g.,
/page-2/rubiks-cube.
Refer the code given below.
import { Link } from "@magicjs.dev/frontend"
import React from "react"
import { Button } from "antd"
export default function Component(props: any) {
return (
<div>
Hello World from page 1
<Link to="/page-2/rubiks-cube">
<Button>Go to page 2: Rubik's Cube</Button>
</Link>
</div>
)
}Refresh the page to see the updated navigation and dynamic rendering based on the route parameter.

🎉 Congratulations! You've learned how to link two pages within the MagicJS framework and utilize route parameters for dynamic page rendering.
Last updated