skip to Main Content

How can I get the url params from a route?
I got this code:

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Routes>

          <Route path="/table/:name/" element={<SortingTable/>}></Route>
          <Route path="" exact element={<BasicTable/>}></Route>
        </Routes>
      </BrowserRouter>
    </div>
  );
}

I want to get the name from the url and use it in SortingTable:

  
const SortingTable = ({match}) => {

    let [searchParams, setSearchParams] = useSearchParams();

    const [data, setData] = useState([])
    const [columns, setColumns] = useState([])
    const table = match.params.name //=> undefined

2

Answers


  1. use useParams from React Router

    import * as React from 'react';
    import { Routes, Route, useParams } from 'react-router-dom';
    
    function ProfilePage() {
      // Get the userId param from the URL.
      let { userId } = useParams();
      // ...
    }
    
    Login or Signup to reply.
  2. You can use the useParams:

    const { name } = useParams();
    

    Note: When you want to get the queries from the URL, you can use the useSearchParams, But when you want to get the params you defined in your Route component and path prop, you can use the useParams

    enter image description here

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