Skip to content

Instantly share code, notes, and snippets.

@danieldram
Last active April 23, 2018 10:04
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 danieldram/9be4608c640e7a57468728f44e57ec94 to your computer and use it in GitHub Desktop.
Save danieldram/9be4608c640e7a57468728f44e57ec94 to your computer and use it in GitHub Desktop.
convert prop camelCase css names into standard dashed css properties to easily use in styled-components and etc.
export const PROPtoCSS = (props) => {
if(Object.keys(props).length==0) return {}
const css ={}
for(let propName in props){
const chars = propName.split(/([A-Z])/g)
const names = chars.map((v, i, arr)=>{
if(v.match(/[A-Z]/)){
arr[i+1] = `${v.toLowerCase()}${arr[i+1]}`
}
return v
}).filter(v => !v.match(/[A-Z]/))
const cssProp = names.join("-")
css[cssProp] = props[propName]
}
return css
}
import {PROPtoCSS} from "./_prop-to-css"
describe("PROPtoCSS", () => {
it('basic case', () => {
const props = {
backgroundColor:"red"
}
const result = PROPtoCSS(props)
const expected = {}
expected["background-color"] = "red"
expect(result).toEqual(expected)
});
it("handles a complex case", () => {
const props = {
gridTemplateAreas:"red"
}
const result = PROPtoCSS(props)
const expected = {}
expected["grid-template-areas"] = "red"
expect(result).toEqual(expected)
})
it("handles a case where not camel", () => {
const props = {
color:"red"
}
const result = PROPtoCSS(props)
const expected = {}
expected["color"] = "red"
expect(result).toEqual(expected)
})
it("handles many keys", () => {
const props = {
color:"red",
backgroundColor: "red",
gridTemplateAreas: "red"
}
const result = PROPtoCSS(props)
const expected = {}
expected["color"] = "red"
expected["background-color"] = "red"
expected["grid-template-areas"] = "red"
expect(result).toEqual(expected)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment