skip to Main Content

I have problem about config React Router v6.14 is how to get param from url to component. I had tried reading React-router documentation about ‘createBrowserRouter’ and ‘useParams’ but I didn’t understood and how to set up it. I had tried set up via code in this . Is this possible to do this?

import { createBrowserRouter, useParams } from "react-router-dom";
import DefaultLayout from "../layout/DefaultLayout";
import FormAuth from "../pages/auth/Auth";
import NotFound404 from "../pages/notfound404/NotFound404";

const GetParam: any = () => {
  let { authPath } = useParams<string>();
  return authPath;
};

export const router = createBrowserRouter([
  {
    path: "/",
    element: <DefaultLayout />,
  },
  {
    path: "/:authPath",
    element: <FormAuth name={GetParam()} />,
  },
  {
    path: "*",
    element: <NotFound404 />,
  },
]);

2

Answers


  1. You are almost there, You have to use useParams on the given route, in your case, in FormAuth.
    When you redirect "/anypath" the component will call useParams and get the params.

    Login or Signup to reply.
  2. I suggest you just render the FormAuth element on the given path (you don’t need to have an additional function in your routes file) and in the component, you can get the parameter using the useParams hook. In your case you can use it like this:

    const { authPath } = useParams();
    

    authPath will be either undefined (if no value is provided) or the value itself.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search