Skip to content

Instantly share code, notes, and snippets.

@moimikey
Last active May 29, 2018 12:57
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 moimikey/4f7b707a5d94b119ceb33f2eb0bd5f25 to your computer and use it in GitHub Desktop.
Save moimikey/4f7b707a5d94b119ceb33f2eb0bd5f25 to your computer and use it in GitHub Desktop.
inline props as styled-component css

@moimikey

Usage

// valid css properties in camelCase (checked by `css-key`)
const props = {
  gridColumnStart: ...,
  gridColumnEnd: ...,
  gridRowStart: ...,
}

const additionalProps = {
  gridRowEnd: ...
}

// inline all of the props, or segments of props
const Grid = styled.div`
  ${props => css`${inlineProps(props).join(';')}`}
  ${props => css`${inlineProps(additionalProps).join(';')}`}
`
import * as React from 'react'
import styled from 'styled-components'
import G from './grid'
const Dashboard = () => (
<G.Grid columns='1fr 1fr'>
<G.Cell>A</G.Cell>
<G.Cell>B</G.Cell>
<G.Cell>C</G.Cell>
<G.Cell>D</G.Cell>
<G.Cell>E</G.Cell>
</G.Grid>
)
export default Dashboard
import * as React from 'react'
import styled, { css } from 'styled-components'
import inlineProps from './inline-props'
const Grid = styled.div`
${props => css`${inlineProps(props).join(';')}`}
`
const Cell = styled.div`
${props => css`${inlineProps(props).join(';')}`}
`
const Cell$ = (props) => {
const cellProps = {
gridColumnStart: props.columnStart,
gridColumnEnd: props.columnEnd,
gridRowStart: props.rowStart,
gridRowEnd: props.rowEnd,
gridColumn: props.column,
gridRow: props.row,
gridArea: props.area,
justifySelf: props.justifySelf,
alignSelf: props.alignSelf,
placeSelf: props.placeSelf
}
return (
<Cell {...cellProps}>
{props.children}
</Cell>
)
}
const Grid$ = (props) => {
const gridProps = {
display: props.display || 'grid',
gridTemplateColumns: props.columns,
gridTemplateRows: props.rows,
gridColumnStart: props.columnStart,
gridTemplateAreas: props.templateAreas,
gridArea: props.area,
gridColumnGap: props.columnGap,
gridRowGap: props.rowGap,
gridGap: props.gap,
justifyItems: props.justifyItems,
alignItems: props.alignItems,
placeItems: props.placeItems,
justifyContent: props.justifyContent,
alignContent: props.alignContent,
placeContent: props.placeContent,
gridAutoColumns: props.autoColumns,
gridAutoRows: props.autoRows,
gridAutoFlow: props.autoFlow,
grid: props.grid
}
return (
<Grid {...gridProps}>
{props.children}
</Grid>
)
}
export default {
Grid: Grid$,
Cell: Cell$
}
import cssKey from 'css-key'
const inlineProps = (props, { skip = ['theme', 'children'] } = {}) =>
Object.keys(props).reduce((acc, label, index, arr) => {
if (new RegExp(skip.join('|')).test(label) || !props[label]) {
return arr
}
arr[index] = `${cssKey(label)}: ${props[label]}`
return arr
}, [])
export default inlineProps
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment