1

I use react-router-dom version ^5.1.2 and try to pass dynamic property. My root component looks like this:

export const RegisterRoutes: React.FunctionComponent<RouteComponentProps> = ({
  match,
}: RouteComponentProps) => {
  const root = match.url;

  return (
    <Switch>
      <Route exact path={`${root}/success`} component={RegisterSuccess} />
      <Route exact path={`${root}/success/email`} component={RegisterEmail} />
      <Route exact path={`${root}/confirmation/email/:code`} component={RegisterEmailConfirmation} />
      <Redirect to={root} />
    </Switch>
  );
};

Here is a child RegisterEmailConfirmation component:

export const RegisterEmailConfirmation: React.FunctionComponent<RouteComponentProps> = ({ match }) => {

  console.log(match.params.code) // expected 'code' property from the url 

  return (
     <SomeContent />
    />
  );

I have an url from the BE with dynamic 'code' parameter, it looks like this: register/confirmation/email?code=fjds@dfF. How can I render RegisterEmailConfirmation component and read 'code' property inside? What's wrong with my code?

1 Answer 1

3

As you are using function component you could use useParams hook in your component. See from useParams documentation:

useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current <Route>.

Try as:

export const RegisterEmailConfirmation: React.FunctionComponent<RouteComponentProps> = () => {
  let { code } = useParams();

  console.log(code);

  return <>
     { /* your implementation */ }
  </>
}

Also you can import as:

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

I hope this helps!

Sign up to request clarification or add additional context in comments.

4 Comments

seems, it does not recognize path 'localhost:3000/register/confirmation/email?code=fjds@dfF' and nothing renders
@s_kamianiok What happens if you use the URL as register/confirmation/email/fjds@dfF?
sorry, looks everything is okay. my mistake - I used email?code=fjds@dfF' instead of email/my-dynamic-code
@s_kamianiok Awesome, happy to help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.