In my route user/[userId]/forms
, I have a layout.tsx
that includes a Select/Dropdown menu.
The dropdown menu has options with values representing different form IDs. When the user selects an item from the dropdown, I want to navigate to user/[userId]/forms/[formId]
. Currently, I am attempting to achieve this as follows:
import { useRouter, usePathName, useParams } from "next/navigation";
const router = useRouter();
const pathName = usePathName();
const params = useParams();
const handleOnChange = (formId: string) => {
if(params.formId) {
router.push(pathName.replace(params.formId, formId)); // Update selected form.
} else {
router.push(`${pathName}/${formId}`); // Open new form.
}
}
This method works, but it seems manual and potentially unreliable. If the URL contains a string matching the form ID, it could be unintentionally replaced. Is there a more robust way to set the value of a dynamic route segment?