Skip to content

Instantly share code, notes, and snippets.

@smashercosmo
Last active January 27, 2020 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smashercosmo/4bfcef8c884f82a320c2a85a456aae68 to your computer and use it in GitHub Desktop.
Save smashercosmo/4bfcef8c884f82a320c2a85a456aae68 to your computer and use it in GitHub Desktop.
VerticalStackV2
import React from 'react'
import { VerticalStack } from '../VerticalStack2/VerticalStack2'
export function App() {
return (
<VerticalStack gap={10} passthrough skipLast>
<h1>Hello world</h1>
<p>Bla bla bla</p>
<p>Bla bla bla</p>
</VerticalStack>
)
}
.gap10 {
margin-bottom: 10px;
}
.gap20 {
margin-bottom: 20px;
}
.gap30 {
margin-bottom: 30px;
}
.gap40 {
margin-bottom: 40px;
}
.gap50 {
margin-bottom: 50px;
}
import React from 'react'
import cx from 'classnames'
import styles from './VerticalStack2.css'
function getClassName(el: React.ReactElement<any>) {
return (el.props && el.props.className) || ''
}
type VerticalStackProps = {
children: React.Node
className?: string
gap?: 10 | 20 | 30 | 40 | 50
passthrough?: boolean
skipLast?: boolean
skipFirst?: boolean
}
function VerticalStack(props: VerticalStackProps) {
const {
children,
className,
passthrough,
skipLast,
skipFirst,
} = props
const classes = cx({
[styles[`gap${String(gap)}`]]: gap > 0,
})
if (passthrough) {
return (
<>
{React.Children.map(
children as React.ReactElement[],
(child, index) => {
if (skipLast && index === React.Children.count(children) - 1) {
return child
}
if (skipFirst && index === 0) {
return child
}
return React.cloneElement(child, {
className: cx(getClassName(child), className, classes),
})
},
)}
</>
)
}
return <div className={cx(className, classes)}>{children}</div>
}
export { VerticalStack }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment