Magofoco
Magofoco

Reputation: 5476

Match multiple exact routes

I am creating a function that checks if the current url matchs exactly the format I want.

I want to "check in bulk" if the current URL is part of an acceptable list of URLs.

I managed to do it with REGEX:

  const validateOpinionPath = (currentUrl: string): boolean => {

    const regexPatter = /opinion\/[0-9a-z-]*\/(large|medium|small)$/g
    const matchResult = currentUrl.match(regexPatter)
    return !!matchResult
  }

HOWEVER I would like to know how can I do the same by using matchPath (or any other function provided by react-router-dom).

I tried the following but it matches only the first URL:

  const validateOpinionPath = (currentUrl: string): boolean => {
    const match = matchPath(currentUrl, {
      path:
        '/option/:opinionId/large' ||
        '/option/:opinionId/medium' ||
        '/opinion/:opinionId/small',
      exact: true,
      strict: false
    })

    return !!match
  }

I want to match exactly these routes:

 '/option/:opinionId/large',
 '/option/:opinionId/medium',
 '/opinion/:opinionId/small'

'/option/:opinionId/large/something' should return false

Upvotes: 1

Views: 1799

Answers (3)

Kirill Skomarovskiy
Kirill Skomarovskiy

Reputation: 1575

React router dom uses path-to-regexp.

Your path can be:

/option/:optionId/(small|medium|large)

Upvotes: 0

Yousaf
Yousaf

Reputation: 29354

Reason why multiple strings separated by || operator doesn't works is because second string will only be selected as the value of the path property if first string is a falsy value, for example an empty string.

Since, in your case, first string is not a falsy value, value of the path property is always the first string, i.e. '/option/:opinionId/large'.

Solution

You can pass an array of strings as a value of path property in options object passed to matchPath(). This way each path will be checked instead of just the first one.

const match = matchPath(currentUrl, {
  path: [
     '/option/:opinionId/large',
     '/option/:opinionId/medium',
     '/opinion/:opinionId/small'
  ],
  exact: true,
  strict: false
})

Upvotes: 2

Veno
Veno

Reputation: 445

I hope this will work!

    const validateOpinionPath = (currentUrl: string): boolean => {
      const match = matchPath(currentUrl, {
        path: '/option/:opinionId/*'
        exact: true,
        strict: false
      })
      return !!match
    }

Upvotes: 0

Related Questions