react-route-dom v6 TypeError: Cannot read properties of undefined (reading 'state')

Viewed 49

I am having trouble passing state to the component destination specified in Navigate.

    "react": "~18.1.0",
    "react-router-dom": "^6.3.0",

send ${address} valiable

  • from Wallet.js
    import { useNavigate } from "react-route-dom";

    const Wallet = ({ address, amount, symbol, destroy }) => {
        const navigate = useNavigate();
        return (
            <div>
                <button>
                    onClick={() =>
                    navigate("/booked", { state: { address: `${address}` } })
                    }
                </button>
            </div>
        );
    };
  • to RoomManagement.js
    import { useLocation } from "react-router-dom";

    const RoomManagement = () => {
        const { location } = useLocation();
        console.log("get address: ", location);
    }

But in console:

enter image description here

I tried to access, but it gives me an error.:

enter image description here

What would need to be modified?

1 Answers

location is the object returned from the useLocation hook. state would then be destructured from location.

Examples:

const RoomManagement = () => {
  const location = useLocation();

  useEffect(() => {
    console.log("get address: ", location.state?.address);
  }, [location]);

  ...
}

or

const RoomManagement = () => {
  const { state } = useLocation();

  useEffect(() => {
    console.log("get address: ", state?.address);
  }, [state]);

  ...
}
Related