1

I have created a map with new Map() to store my RR4 configuration in my app.

I want to access the values of /countries/:id, when I get /countries/1

routesMap.get('/countries/1') 
// should return the same as to routesMap.get('/countries/:id')

routesMap.get('/countries/1/comments/20'); 
// should match routesMap.get('/countries/:countryId/comments/:id')

By creating a class from Map, how can I tweak the get so it become more intelligent to get my react-router-dom path ?

1
  • Create a parent component that wraps your react router and store the info that you need in a redux-state, or a react context, then retrieve this state in child components that need it. Commented Feb 24, 2019 at 6:17

1 Answer 1

1

A simple attempt would be something like the following

class RouteMap extends Map {
  get(key) {
    let match;
    // exact match
    if (this.has(key)) return super.get(key);
    
    // not exact match, need to apply logic
    for (let route of this.keys()) {
      const reg = new RegExp(`^${route.replace(/:\w+/g,'\\w+')}$`);
      if (!match && reg.test(key)) match = route;
    }
    return super.get(match);
  }
}


const routesMap = new RouteMap();
routesMap.set('/countries/:id', 'just id')
routesMap.set('/countries/:countryId/comments/:id', 'id and country')


console.log(routesMap.get('/countries/:id'));
console.log(routesMap.get('/countries/1'));

console.log(routesMap.get('/countries/:countryId/comments/:id')); 
console.log(routesMap.get('/countries/1/comments/20'));

But might need further work to become more flexible, performant and handle edge cases like trailing / etc.

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

Comments

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.