2

I have the following code. (Also available on CodeSandbox: https://codesandbox.io/s/dreamy-aj-sxs411?file=/src/index.js)

App.js

import { Route, Routes } from "react-router-dom";
import Test01 from "./Test01";
import Test02 from "./Test02";

function App() {
  return (
    <Routes>
      <Route path="/" element={<Test01 />} />
      <Route path="/test02" element={<Test02 />} />
    </Routes>
  );
}

export default App;

Test01.js

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

function Test01() {
  const pathname = "/test02";
  const docId = "12345";

  return (
    <div>
      <Link to={{ pathname: pathname, state: { docId: docId } }}>
        Go to target page with docId
      </Link>
    </div>
  );
}

export default Test01;

Test02.js

import React from "react";
import { useLocation } from "react-router-dom";

function Test02() {
  const location = useLocation();
  const docId = location.state?.docId || "Default Doc ID";

  return (
    <div>
      <h1>Target Page</h1>
      <p>Doc ID: {docId}</p>
    </div>
  );
}

export default Test02;

If I run the react page, I can not get the correct docId, and it only shows the Default Doc ID. What is wrong here?

Ham Dong Kyun
  • 756
  • 4
  • 28

1 Answers1

2

The state should be a separate prop within Link, rather than part of the to prop:

      <Link state={{ docId: docId }} to={{ pathname: pathname }}>
        Go to target page with docId
      </Link>
motto
  • 2,888
  • 2
  • 2
  • 14
  • Thanks. That was super simple, but somehow chat gpt4 missed it. – Ham Dong Kyun Mar 18 '23 at 14:29
  • @HamDongKyun That's good news, I guess we get to keep our jobs for another few months! For what it's worth, the typescript definitions catch this error immediately – could be worth considering TS if you have control over the project. – motto Mar 18 '23 at 14:58