Last active
March 18, 2023 16:28
-
-
Save goldhand/70de06a3bdbdb51565878ad1ee37e92b to your computer and use it in GitHub Desktop.
Parse html style string for a react component
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
/** | |
* @function parseStyles | |
* Parses a string of inline styles into a javascript object with casing for react | |
* | |
* @param {string} styles | |
* @returns {Object} | |
*/ | |
const parseStyles = styles => styles | |
.split(';') | |
.filter(style => style.split(':')[0] && style.split(':')[1]) | |
.map(style => [ | |
style.split(':')[0].trim().replace(/-./g, c => c.substr(1).toUpperCase()), | |
style.split(':')[1].trim() | |
]) | |
.reduce((styleObj, style) => ({ | |
...styleObj, | |
[style[0]]: style[1], | |
}), {}); |
👍 this is helpful, thank you
In https://reactjs.org/docs/dom-elements.html#style written:
...Vendor prefixes other than ms should begin with a capital letter. ...
So:
style.split(':')[0].trim().replace(/-./g, c => c.substr(1).toUpperCase())
must be replaced with:
style.split(':')[0].trim().replace(/^-ms-/, 'ms-').replace(/-./g, c => c.substr(1).toUpperCase())
This code will significantly improve the performance :
const convertStylesStringToObject = stringStyles => typeof stringStyles === 'string' ? stringStyles
.split(';')
.reduce((acc, style) => {
const colonPosition = style.indexOf(':')
if (colonPosition === -1) {
return acc
}
const
camelCaseProperty = style
.substr(0, colonPosition)
.trim()
.replace(/^-ms-/, 'ms-')
.replace(/-./g, c => c.substr(1).toUpperCase()),
value = style.substr(colonPosition + 1).trim()
return value ? {...acc, [camelCaseProperty]: value} : acc
}, {}) : {}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A minor improvement for line 13, to make background-images with "http://" survive:
style.split(':').slice(1).join(':').trim()