remix-run / react-router

Declarative routing for React
https://reactrouter.com
MIT License
52.78k stars 10.22k forks source link

[Bug]: generatePath/matchPath don't handle encoding/decoding `/` the same #11940

Open cbix opened 3 weeks ago

cbix commented 3 weeks ago

What version of React Router are you using?

6.26.1

Steps to Reproduce

It is expected that a pathname created with generatePath matches the given path in matchPath, Route etc. and yields the input parameters basically unchanged. This is not the case if a parameter contains a slash:

const path = '/a/:b/c';
const b = '1/2';
console.log(matchPath({ path }, generatePath(path, { b })));

React example:

const path = '/a/:b/c';
const params = { b: '1/2' };

const Match = () => {
  const { b } = useParams<'b'>();
  return <h1>Hello {b}</h1>
};

const Test = () => {
  return (
    <BrowserRouter>
      <Link to={generatePath(path, params)}>Click me</Link>
      <Routes>
        <Route path={path} element={<Match />} />
        <Route path="*" element={<h1>No match :(</h1>} />
      </Routes>
    </BrowserRouter>
  );
};

Expected Behavior

I expect the match params to be the same as the params passed to generatePath:

{
  params: { b: '1/2' },
  pathname: '/a/1%2F2/c',
  pathnameBase: '/a/1%2F2/c',
  pattern: { path: '/a/:b/c' },
}

React example:

<h1>Hello 1/2</h1>

Actual Behavior

null

React example:

<h1>No match :(</h1>

Worth noting that matchPath seems to work as expected and decodes %2F to /, however generatePath doesn't encode / to %2F. A workaround for this would be to use encodeURIComponent together with generatePath in cases where this is expected to happen, but actually we don't want to encode all special characters.

Another perspective would be that generatePath is working correctly but matchPath isn't, however there might be ambiguities for multiple parameters (/:foo/:bar) which would need to be ruled out by defining some lookahead logic for matching.

Related issues

tigerabrodi commented 2 weeks ago

I'm encountering the same issue.