3 ms·
Drives me nuts that there's no straightforward way to do a switch statement in JSX. <Layout> <Header /> {switch (page) { case 'home': return <H
by Eric_WVGG 5y ago
Drives me nuts that there's no straightforward way to do a switch statement in JSX.
<Layout>
<Header />
{switch (page) {
case 'home': return <Home />
case 'about': return <About />
default: return <NotFound />
}}
<Footer />
</Layout>
- 9wzYQbTYsAIc 5y agoThe example you put forward could be resolved through using a router. The router implementations are essentially fancy switches without ”switch”.
- Eric_WVGG 5y agoyeah, I use reach/router for this kind of thing. A page switcher was just the first example that popped into my head. Here's a real world example if it matters… const Grid = (gridItems) => ( <Grid> {gridItems.map(item => ( <GridItem {...item} key={item._key} /> _} </Grid> )} const GridItem = (props) => { switch(props._type) { case 'image': return <GridImage {...props} /> case 'video': return <GridVideo {...props} /> case 'copy': return <GridCopy {...props} /> // slideshows, 3D stuff, newsletter signup forms… default: return <></> } } … and I suppose a case could even be made for the granularity of this superfluous <GridItem /> component… but regardless this is just a minor annoyance that comes up from time to time.
- methyl 5y agoI'd write it like this const gridComponent = { image: GridImage, video: GridVideo, copy: GridCopy } const Grid = (gridItems) => ( <Grid> {gridItems.map(item => { const GridComponent = gridComponent[item._type] return GridComponent ? <GridComponent {...item} key={item._key} /> : null }} </Grid> )}
- 9wzYQbTYsAIc 5y agoThat’s definitely representative of the compactness that is possible with modern JSX.
- bern4444 5y agoI'm surprised this doesn't work since you could easily externalize this to a function: <Layout> <Header /> {getCorrectComponent(page)} <Footer /> </Layout> const getCorrectComponent = (page) => { switch (page) { case 'home': return <Home /> case 'about': return <About /> default: return <NotFound /> } }
- Eric_WVGG 5y agothat does work. imo ugly, not straightforward
- uhoh-itsmaciek 5y agoYeah, this is generally a good compromise. I sometimes like to write these as helper components instead: <Layout> <Header /> <Content page={page} /> <Footer /> </Layout> const Content = ({page}) => { switch (page) { case 'home': return <Home /> case 'about': return <About /> default: return <NotFound /> } }
- hombre_fatal 5y agoYou could of course wrap the switch in a self-invoking function: {() => { switch... }()} Sometimes an inline switch is indeed the clearest code. The closest JS has is the do-expression proposal: { do { switch... }}