I'm upgrading react-router-dom from v5 to v6 in a codebase I'm not entirely familiar with yet, and I am curious about how to replace the following code:
const history = useHistory();
history.replace(url, params);
In the docs they only display what you would do to replace in case there's 1 argument. so if I had:
history.replace(url)
I'd simply do:
const navigate = useNavigate();
navigate(url, {replace: true})
How do I ensure the second argument is kept with the useNavigate hook?
I'm tempted to do this:
const navigate = useNavigate();
navigate(url, params)
or
const navigate = useNavigate();
navigate(url, { state: params })
How should it be replaced without any impacts?
The state is sent in the second parameter under the state property, same as indicating a redirect (REPLACE) vs navigate (PUSH).
The useNavigate hook returns a navigate function:
declare function useNavigate(): NavigateFunction; interface NavigateFunction { ( to: To, options?: { replace?: boolean; state?: any } ): void; (delta: number): void; }
Note that the second argument is an options arg with replace and state properties.
| Action | v5 history = useHistory() |
v6 navigate = useNavigate() |
|---|---|---|
| Navigate | history.push(url) |
navigate(url) |
| Redirect | history.replace(url) |
navigate(url, { replace: true }) |
| Navigate w/state | history.push(url, params) |
navigate(url, { state: params }) |
| Redirect w/state | history.replace(url, params) |
navigate(url, { replace: true, state: params }) |
navigate(url, params) would only work if params is an object with replace and/or state properties, e.g. { replace: true, state: { ... } }.