SolidJS provides various control flow components for conditional rendering and list rendering:
Conditional Rendering:
javascript// Show - Conditional rendering (similar to React's conditional rendering) <Show when={isLoggedIn()} fallback={<Login />}> <Dashboard /> </Show> // Switch - Multiple condition branches <Switch fallback={<NotFound />}> <Match when={status() === 'loading'}> <Loading /> </Match> <Match when={status() === 'success'}> <Success /> </Match> <Match when={status() === 'error'}> <Error /> </Match> </Switch>
List Rendering:
javascript// For - List rendering (recommended) <For each={items()}> {(item, index) => ( <div> {index()}: {item.name} </div> )} </For> // Index - Use index as key (better performance) <Index each={items()}> {(item, index) => ( <div> {index}: {item().name} </div> )} </Index>
Dynamic Components:
javascript// Dynamic - Dynamic component rendering <Dynamic component={currentComponent()} props={props} /> // Portal - Portal to other DOM nodes <Portal mount={document.getElementById('modal-root')}> <Modal /> </Portal>
Suspense - Async Loading:
javascript<Suspense fallback={<Loading />}> <AsyncComponent /> </Suspense> // Nested Suspense <Suspense fallback={<Skeleton />}> <Suspense fallback={<LoadingAvatar />}> <UserAvatar /> </Suspense> <Suspense fallback={<LoadingPosts />}> <UserPosts /> </Suspense> </Suspense>
ErrorBoundary - Error Boundary:
javascript<ErrorBoundary fallback={(err) => <ErrorPage error={err} />}> <Component /> </ErrorBoundary>
Best Practices:
- Use
Forinstead ofmapfor list rendering - Use
Indexwhen list item order doesn't change - Use
Showfor simple conditional logic - Use
Switchfor multiple condition branches - Use
Suspensefor async components