Home > front end >  React useParams returns undefined
React useParams returns undefined

Time:12-13

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

CodePudding user response:

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();

CodePudding user response:

When using useParams, you have to match the destructure const {id} = useParams(); to your path "/path/:id".

import { useParams } from "react-router-dom";

export default function fn() {
    const { id } = useParams();
    console.log("this.context:",  id )

    return (
      <div className="....">
        {/* render something based on id */}
      </div>
    )
}
  • Related