DEV Community

Discussion on: Useful tips and tricks React/js - part1

Collapse
 
josemunoz profile image
José Muñoz

I have a different approach to the object switch cases. Instead of:

const aSwitchCase = gotItFromSomewhere();

return (
    <>
        {
            {
                case1: <Component1 />
                case2: <Component2 />
                case3: <Component3 />
                case4: SomeFunctionThatReturnsAComponent()
                case5: "yeah anything it's an object and the 'aSwitchCase' is referencing the property"
                "undefined": () => throw Error("Havent' really tried this one but I think it'll work maybe? Please comment if it doesn't I'll delete this.")
                "null": () => throw Error("ditto above")
            }[`${aSwitchCase}`]
        }
    </>
)

I wrap the components into a function and use optional chaining to extract the content, you could call it a monad if you like:

const aSwitchCase = gotItFromSomewhere()
const content =  {
                case1: () => <Component1 />,
                case2: () => <Component2 />,
                case3: () => <Component3 />,
                case4: SomeFunctionThatReturnsAComponent,
            }[aSwitchCase]

return content?.()
Collapse
 
fly profile image
joon • Edited

Thank you for the feedback.

I totally agree and now I don't think I'll ever use switch cases anymore. :)