Skip to content

Instantly share code, notes, and snippets.

@tammyhart
Last active November 3, 2024 22:10
Show Gist options
  • Save tammyhart/8019f82d1bbc9fc0fd732e4c528cd14e to your computer and use it in GitHub Desktop.
Save tammyhart/8019f82d1bbc9fc0fd732e4c528cd14e to your computer and use it in GitHub Desktop.
FilteredComponentAs.tsx - Strapi and Styled-Components filter
import styled from "styled-components"
import type { KnownTarget } from "styled-components/dist/types"
import { type BlocksContent, BlocksRenderer } from "@strapi/blocks-react-renderer"
type FilterAs = {
filteredText: string
as?: KnownTarget
}
const filterAs = (text: string): FilterAs => {
const match = text.match(/%(h[1-6]|p)\b/)
const asString = match ? match[0] : undefined
const filteredText = asString ? text.replace(asString, "") : text
const as = asString
? (asString.replace("%", "").toLowerCase() as KnownTarget)
: undefined
return { filteredText, as }
}
type ComponentProps = {
children: React.ReactNode
as?: KnownTarget
}
type FilteredComponentAs = {
children: React.ReactNode
Component: React.ComponentType<ComponentProps>
}
const FilteredComponentAs = ({ children, Component }: FilteredComponentAs) => {
const as = React.Children.toArray(children).reduce<KnownTarget | undefined>(
(acc, child) => {
if (React.isValidElement(child) && child.props.text) {
const filtered = filterAs(child.props.text)
return filtered.as || acc
}
return acc
},
undefined
)
const filteredChildren = React.Children.toArray(children).map(child => {
if (React.isValidElement(child) && child.props.text) {
const { filteredText } = filterAs(child.props.text)
return filteredText
}
return child
})
return (
<Component as={as}>
{filteredChildren}
</Component>
)
}
const H1 = styled.h1`
// h1 styles
`
// ... rest of heading components ...
type Content = {
content: BlocksContent
}
const Content = ({ content }: Content) => (
<BlocksRenderer
content={content}
blocks={{
heading: ({ children, level }) => {
const Heading = [H1, H2, H3, H4, H5, H6][Number(level) - 1]
return (
<FilteredComponentAs Component={Heading}>
{children}
</FilteredComponentAs>
)
},
// ... rest of blocks ...
}}
/>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment