Search code examples
javascriptreactjsreact-router-dom

Pass data to a component with useNavigate from React Router Dom


I'm using useNavigate to go to the component and need to pass data (state) to this ChatRoom component when I click a button. The component is on the route /chatroom. I'm using React Router Dom v6. I have read the documentation but cannot find what I'm looking for.

export default function Home() {
  const [username, setUsername] = useState("");
  const [room, setRoom] = useState("");

  const navigate = useNavigate();

  const handleClick = () => {
    navigate("/chatroom");
  };

  return (
    <button
      type="submit"
      className="btn"
      onClick={() => {
        handleClick();
      }}
    >
      Join Chat
    </button>
  );
}

Solution

  • You can pass data to the component that corresponds to /chatroom in React Router Dom v6 like this:

    navigate('/chatroom', { state: "Hello World!" });
    

    And consume it with the help of useLocation hook this way:

    import { useLocation } from "react-router-dom";
    function ChatRoom() {
      const { state } = useLocation();
      return (
        <div>
          {state}
        </div>
      );
    }
    export default Chatroom;
    

    If you wanna pass multiple values, use an object, like so:

    navigate('/chatroom', { state: {id:1, text: "Hello World!"} });
    

    And consume it again with useLocation hook this way:

    import { useLocation } from "react-router-dom";
    function ChatRoom() {
      const { state } = useLocation();
      return (
        <div>
          id: {state.id}
          text: {state.text}
        </div>
      );
    }
    export default Chatroom;