Search code examples
javascriptreactjsstringswitch-statementtemplate-strings

How to match a template string in switch statement with js?


I have a function that returns a component that depends on the pathname of the window.

getComponentByPathname = (pathname) => {
    switch(patname){
      case "/view1": return <ViewOneComponent>;
      case "/view2": return <ViewTwoComponent>;
}

But the problem starts when I try to evaluate a template string that has one id

getComponentByPathname = (pathname) => {
    switch(pathname){
      case "/view1": return <ViewOneComponent>;
      case "/view2": return <ViewTwoComponent>;
      case `/view3/${getId()}`: return <ViewThreeComponent>;

}

It's only working with the first two cases. Why? Also, I make another attempt. In this case, I literally paste the string with the Id in the third case, like this:

case "view3/1234567": return <ViewThreeComponent>;

And works. But the problem is that I can not hardcode the id in the string.

How I can evaluate that?


Solution

  • My guess would be that getId() is returning a different value then what you expect. I would try the following and make that getId() is returning the expected value when it is being calculated

    getComponentByPathname = pathname => {
      const case3 = `/view3/${getId()}`;
      console.log(`case3 = ${case3}`);
      console.log(`pathname = ${pathname}`);
    
      switch (pathname) {
        case '/view1':
          return <ViewOneComponent>;
        case '/view2':
          return <ViewTwoComponent>;
        case case3:
          return <ViewThreeComponent>;
      }
    };
    

    But if you only need to decide which component to render based on your path then something like this might be more appropriate

    const examplePaths = ['view1/', 'view2/', 'view3/', 'view3/1241232', 'view3/8721873216', 'view4/', 'vi/ew1', ''];
    
    const mapper = {
      view1: 'ViewOneComponent',
      view2: 'ViewTwoComponent',
      view3: 'ViewThreeComponent'
    };
    
    examplePaths.forEach(ent => {
      const splitPaths = ent.split('/');
    
      const mapped = mapper[splitPaths[0]];
      if (mapped) {
        console.log(mapped);
      } else {
        console.log('Path not supported');
      }
    });