Home > Back-end >  react-router-dom: How to match urls with some pattern
react-router-dom: How to match urls with some pattern

Time:10-31

I have urls like

/detail/sbc-123
/detail/tresds-121212
/detail/xywh-1

How to write the router for this and get the string sbc-123

CodePudding user response:

You have two options by docs

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

function App() {
  return (
    <Route
      path="/detail/:exact"
      render={({ match }) => {
        /* Do whatever you want with the match... */
        return <div />;
      }}
    />
  );
}


// Or you can just
import { useRouteMatch } from "react-router-dom";

function Component() {
  let match = useRouteMatch("/detail/:exact");

  // Do whatever you want with the match...
  return <div />;
}

a match object contains useful information the given argument is its path and you can access the correct path via the URL field

match.path // '/details/:exact'
match.url // '/detail/sbc-123'
  • Related