Search code examples
next.jsnavigation

How can I define a route for a component with Next js?


On my Next.js version 14 app, I have a page.tsx file on my app/tasks folder. On that page I have a button that opens a Dialog/Pop-up to edit a task: enter image description here

How can I change the route to tasks/edit when opening the edit Dialog component ?

This is my app folder structure so far:

enter image description here


Solution

  • to change the route to /tasks/edit when opening the edit Dialog component in your Next.js version 14 app, you can use the useRouter hook provided by Next.js.

    In your page.tsx file, you can do something like this:

    import { useRouter } from 'next/router';
    
    const YourPageComponent = () => {
    const router = useRouter();
    
    const handleEditButtonClick = () => {
    // edit button cicked: Navigate to the edit route 
    router.push('/tasks/edit');
    };
    
    return (
      <div>
        {/* Your content */}
        <button onClick={handleEditButtonClick}>Edit Task</button>
       {/*content other components */}
     </div>
    );
    };
    
    export default YourPageComponent;
    

    This code snippet assumes that your page.tsx file is located in the tasks folder and is responsible for rendering the page where the edit button is present. Adjust the paths and logic according to your specific requirements.