Last active
April 23, 2018 10:04
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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