Search code examples
javascriptreactjsreact-router-dom

React Router v6 useNavigate() doesn't navigate if replacing last element in path


I have a react component with the following function

    const handleNavigate = (clientId) => {
        console.log(clientId)
        navigate(`/dashboard/clients/${clientId}`)
    }

The console.log() is showing the ID I want to append to use in the navigate function.
AND
The URL in the browser is updating.

But the page does not change.

This works to navigate from /dashboard/clients to /dashboard/clients/foo

but it does not work to navigate from /dashboard/clients/foo to /dashboard/clients/bar

The clientId is passed into the card like so...

const CompanyCard = (props) => {
    const { client, showWatchlist, removeDisabled, showRemove, removeType } = props
...
}

then in the card

                <CardActionArea
                    onClick={() => handleNavigate(client._id)}
                 ...

Any ideas?
Thanks

UPDATE

After reading up from @redapollos suggestion I tried Outlet and the

useRoutes methods... neither worked.

import { useRoutes } from 'react-router-dom'

// then in the routes...

        { path: 'clientdetail/:id', element: <ClientDetail /> },
        { path: 'clientdetail/', element: <ClientDetail /> },

This might be due to using the useRoutes hook but I am still working on it.

Another question here on SO that might get an answer sooner - https://stackoverflow.com/a/70009104/13078911


Solution

  • I just read in React Router Dom Docs v6 this solution:

    import { useNavigate } from 'react-router-dom';
    ...
    const navigate = useNavigate();
    ...
    <Button onClick={() => navigate('../user', { replace: true })}>Register</Button>
    

    So, basically I added ../ before the route and the replace: true.
    Reference: https://reactrouter.com/en/6.9.0/hooks/use-navigate

    It worked for me, hope it works for u! (: