Last active
July 10, 2024 08:53
-
-
Save Profesor08/163e51b5f3cc6cd28138bfb9c01f04dd to your computer and use it in GitHub Desktop.
Convert style string to CSSProperties
This file contains hidden or 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 camelCase from "lodash/camelCase"; | |
export const styleToCSSProperties = (style: string = "") => { | |
return style | |
.trim() | |
.split(";") | |
.map((rule) => { | |
const [key, value] = rule.trim().split(":"); | |
return { | |
key: key?.trim(), | |
value: value?.trim(), | |
}; | |
}) | |
.filter( | |
( | |
rule, | |
): rule is { | |
key: string; | |
value: string; | |
} => rule.key !== undefined && rule.value !== undefined, | |
) | |
.reduce<React.CSSProperties>((props, { key, value }) => { | |
return { | |
...props, | |
[camelCase(key)]: value, | |
}; | |
}, {}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment