React Routes and Components prop mix

Viewed 26

I have the following line of code:

<Route path="/users/:id" exact ><User url={structure.users} /></Route>

In User component I do the following:

function User(props, {match}) {


    useEffect(() => {
        console.log(match);
        console.log(props);
    }, [props]);
    // ...
}

I removed a bit of the code because I only want to show what is necessary but here I see that match is undefined but it should have match.params.id from the link. How can I achieve this so i can make the full url with the url with the attached id?

1 Answers

React components receive only a single props object argument.

Use the Route's render prop so you can pass the route props on to the component.

<Route
  path="/users/:id"
  exact
  render={routeProps => <User url={structure.users} {...routeProps} />}
/>

Alternatively you can use the useParams React hook to access match.params of the current Route.

import { ...., useParams, .... } from 'react-router-dom';

function User(props) {
  const { id } = useParams();

  useEffect(() => {
    console.log(id);
    console.log(props);
  }, [props]);
  // ...
}
Related