skip to Main Content

i want this to be mapping instead of hard coding the cases

const wCategory = () => {
        switch (categoryhovered) {
            case 1:
                return <SalePriceCtg />
            case 2:
                return <ArticlesCtg />
            default:
                return <div>smth3</div>
        }
    }

i cant map the cases so im searching for a better way to do it

2

Answers


  1. Here is a way to use an object instead of a switch statement:

    const wCategory = () => {
        const categories = {
            1: <SalePriceCtg />,
            2: <ArticlesCtg />,
            default: <div>smth3</div>
        };
    
        return categories[categoryhovered] || categories.default;
    };
    
    Login or Signup to reply.
  2. You can use an object to map the cases instead of hardcoding them with a switch statement

    const categoryMap = {
    1: SalePriceCtg,
    2: ArticlesCtg,
    // add more cases here
    };
    
    const wCategory = () => {
    const Component = categoryMap[categoryhovered];
    return Component ? <Component /> : <div>smth3</div>;
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search