🚀 Ship faster with premium components 🚀
Search documentation v1.5.0

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:

Preview
Avatar
How to use ConditionalWrapper in Astro
---
import { ConditionalWrapper } from 'webcoreui/astro'
const condition = false
---
<ConditionalWrapper condition={condition}>
<figure slot="wrapper">
children
<figcaption>Avatar</figcaption>
</figure>
<img src="avatar.png" />
</ConditionalWrapper>
How to use ConditionalWrapper in Svelte
<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>
How to use ConditionalWrapper in React
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 Component

The component expects the following props and setup depending on the framework:

  • Astro: Define an element with a slot called wrapper inside the component. Inside the wrapper slot, specify the place where child elements should be placed using the children string. Anything outside the wrapper slot will be rendered without the wrapper element if the condition prop is false.
  • Svelte: Specify the element prop on the ConditionalWrapper to tell Svelte which HTML tag should be used for wrapping. Defaults to div. You can pass any other HTML attributes on the ConditionalWrapper component to pass along to your wrapper element.
  • React: The React component uses a render prop. Pass your wrapper in to the wrapper prop, which accepts a callback function with a children prop that helps you render your children in placements.

API

type ConditionalWrapperProps = {
condition: boolean
}
type ReactConditionalWrapperProps = {
wrapper: (_: React.ReactNode) => any
} & ConditionalWrapperProps
PropPurpose
condition Pass a condition to decide whether to wrap an element or not.

Changelog

  • v0.8.1 Fixed TypeScript errors when using component with extra props.
  • v0.0.7 Added in version.

Request improvement for this page