Skip to content

Instantly share code, notes, and snippets.

@yairEO
Last active March 2, 2021 09:42
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 yairEO/23ad75a1072e56f4271ca82b0c80047d to your computer and use it in GitHub Desktop.
Save yairEO/23ad75a1072e56f4271ca82b0c80047d to your computer and use it in GitHub Desktop.
React props to CSS variables

Converts props into css variables in styled-components

Example usage

import React from 'react'
import styled from '@xstyled/styled-components'
import { cx, getCSSVars } from 'utils'

const StyledIconBase = styled.i`
  display: inline-block;
  width: var(--size, 24px);
  height: var(--size, 24px);
  transition: .1s;
  mask-image: var(--src);
  background: gray;
`

// will generate "--size" & "--src" variables from the react props
const StyledIcon = styled(StyledIconBase)`
  ${getCSSVars('size', 'src')}
`

// using icons from:
// https://svgbox.net/
const Icon = ({ src = '', size, className }) =>
  <StyledIcon className={cx('icon', className)} size={size} src={`url(https://${src})`} />

export default React.memo(Icon)
export default (...whitelistProps) => (props) => {
const res = Object.entries(props)
.filter(([k, v]) => (typeof v === 'string' || typeof v === 'number') && whitelistProps.includes(k))
.map(([k, v]) => `--${k}:${v};`)
return res
}
@yairEO
Copy link
Author

yairEO commented Mar 2, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment