Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading