0

I wrote some code to get an entity indicator id from the end of a route in a React component:

const pathname = this.props.location.pathname;
const lastPathPart = pathname.split('/').slice(-1)[0];
const requestedJobId = Number(lastPathPart);

The code above gets the requested job id from the end of the route as needed/expected but is there a more proper or structured way to do this in React?

iron.man.rball
  • 109
  • 1
  • 5

1 Answers1

0

1. If it's a functional component, You can use react-router's useParams hook.

Example:

Let's assume this is your route.

<Router>
   <Switch>
      <Route path="/:id" children={<User />} />
   </Switch>
</Router>

Now you can use the useParams hook to extract the id inside the User component like this.

import { useParams } from "react-router";

function User() {
  let { id } = useParams();
  return <h2>User {id}</h2>;
}

2. If it's a class component you can refer to this solution.

Rukshan Jayasekara
  • 1,945
  • 1
  • 6
  • 26