Skip to content

Instantly share code, notes, and snippets.

@Profesor08
Last active July 10, 2024 08:53
Show Gist options
  • Save Profesor08/163e51b5f3cc6cd28138bfb9c01f04dd to your computer and use it in GitHub Desktop.
Save Profesor08/163e51b5f3cc6cd28138bfb9c01f04dd to your computer and use it in GitHub Desktop.
Convert style string to CSSProperties
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