1

In React(with react-router-dom@5.3.0), Link to={PATH} works but Link to={{pathname:PATH}} does not work. I don't know why.

Here is my code:

<Link to={`/chat_detail?name=${user?.name}&room=TestRoom`}>
  <div>TestBtn1</div>
</Link>

<Link to={{ pathname:`/chat_detail?name=${user?.name}&room=TestRoom` }}>
  <div>TestBtn2</div>
</Link>
  1. TestBtn1 works.
  2. TestBtn2 does not work. It shows a blank page and when I refresh on a blank page or directly enter the PATH in the address bar of browser, a page appears.

Is this a bug in react-router-dom?

SteakOverflow
  • 193
  • 1
  • 2
  • 9

1 Answers1

0

You are probably using react-router-dom's version 6 which means that there is no pathname anymore.

According to v5 to v6.3.0 migration guide

If you need to replace the current location instead of push a new one onto the history stack, use navigate(to, { replace: true }). If you need state, use navigate(to, { state }). You can think of the first argument to navigate as your and the other arguments as the replace and state props. The Link component in v6 accepts state as a separate prop instead of receiving it as part of the object passed to to so you'll need to update your Link components if they are using state:

import { Link } from "react-router-dom";

// Change this:
<Link to={{ pathname: "/home", state: state }} />

// to this:
<Link to="/home" state={state} />
Apostolos
  • 10,033
  • 5
  • 24
  • 39
  • Just FYI the `Link` component's `to` prop takes a [`To`](https://github.com/remix-run/react-router/blob/main/packages/router/history.ts#L98) object which can take a partial [`Path`](https://github.com/remix-run/react-router/blob/main/packages/router/history.ts#L35-L50) object, which includes a `pathname` string property. It was the `state` property that got moved. – Drew Reese Oct 12 '22 at 16:09