React useParams returns undefined

I’m writing a React app. I need to capture the url params using useParams().

Below is the relevant code:

import { BrowserRouter as Router, Route, Routes , useParams} from 'react-router-dom';

function App() {
  const {id} = useParams();
  console.log(id)
  };

  return (
    <Router>
      <Routes>
        <Route path=":id" element={<Form/>} >
        </Route>
      </Routes>
    </Router>
  );
}

export default App; 

However, the console.log returns undefined. Any thoughts?

I also tried

const id = useParams(); // did not destructure id

and I tried

<Route path="/:id" element={<Form/>} > //added forward slash before :id

When I’m on localhost:3000/xhyz1, the expected output of the console.log is xhyz1

>Solution :

Cannot access the id in app component because the route is set for form component.

Move the use param inside the form component

function Form() {     

    const {id} = useParams();

Leave a Reply