I need to create a function that parses a CSS string, that will be used on a inline js style.
E.g: what I get is something like const styles = "background-color:#FFFFFF;color:#000000" and I need to transform in:
<h1
className={classes}
style={{ color: fontColor, background: backgroundColor }}
>
{copy}
</h1>
what I do for now is this
const [backgroundColor, setBackgroundColor] = useState();
const [fontColor, setFontColor] = useState();
const colors = styles?.match(/(#)([^;]*)/g);
useEffect(() => {
if (colors) {
if (colors.length > 1) {
setBackgroundColor(colors[0]);
setFontColor(colors[1]);
}
if (colors.length === 1) {
setFontColor(colors[0]);
}
}
}, [colors]);
But I was asked to create pure seperate function that parses the styles string.
So I was wondering if there's a solution where I don't need to "regex" each specific selector and then its value. If there's something like whatever is before the colon is the selector than after that until the semicolon is its value.
Any tips?
Thanks