Conditional Wrapper
Wrap your elements conditionally with a higher order component
Keep your code clean and reduce code duplication with the help of the ConditionalWrapper component which helps you conditionally wrap elements. For example, the following two images are rendered using the ConditionalWrapper component.
In the first scenario, the condition prop that handles whether to wrap the element or not, is set to false, so only an img tag is rendered. In the second scenario, however, the img is wrapped into a figure with a caption, as the condition prop is set to true:

---import { ConditionalWrapper } from 'webcoreui/astro'
const condition = false---
<ConditionalWrapper condition={condition}> <figure slot="wrapper"> children <figcaption>Avatar</figcaption> </figure> <img src="avatar.png" /></ConditionalWrapper><script> import { ConditionalWrapper } from 'webcoreui/svelte'
const condition = false</script>
<ConditionalWrapper condition={condition} element="figure"> <img src="avatar.png" /> {#if condition} <figcaption>Avatar</figcaption> {/if}</ConditionalWrapper>import React from 'react'import { ConditionalWrapper } from 'webcoreui/react'
const condition = false
const Component = () => ( <ConditionalWrapper condition={condition} wrapper={children => ( <figure> {children} <figcaption>Avatar</figcaption> </figure> )} > <img src="avatar.png" /> </ConditionalWrapper>)
export default ComponentThe component expects the following props and setup depending on the framework:
- Astro: Define an element with a
slotcalledwrapperinside the component. Inside thewrapperslot, specify the place where child elements should be placed using thechildrenstring. Anything outside thewrapperslot will be rendered without the wrapper element if theconditionprop isfalse. - Svelte: Specify the
elementprop on theConditionalWrapperto tell Svelte which HTML tag should be used for wrapping. Defaults todiv. You can pass any other HTML attributes on theConditionalWrappercomponent to pass along to your wrapper element. - React: The React component uses a render prop. Pass your wrapper in to the
wrapperprop, which accepts a callback function with achildrenprop that helps you render your children in placements.
API
type ConditionalWrapperProps = { condition: boolean}
type ReactConditionalWrapperProps = { wrapper: (_: React.ReactNode) => any} & ConditionalWrapperProps| Prop | Purpose |
|---|---|
condition | Pass a condition to decide whether to wrap an element or not. |
Request improvement for this page