TransWikia.com

Match multiple exact routes

Stack Overflow Asked by Magofoco on December 20, 2020

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

3 Answers

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
})

Correct answer by Yousaf on December 20, 2020

React router dom uses path-to-regexp.

Your path can be:

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

Answered by Kirill Skomarovskiy on December 20, 2020

I hope this will work!

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

Answered by Veno on December 20, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP