Skip to content

Instantly share code, notes, and snippets.

@goldhand
Last active March 18, 2023 16:28
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save goldhand/70de06a3bdbdb51565878ad1ee37e92b to your computer and use it in GitHub Desktop.
Save goldhand/70de06a3bdbdb51565878ad1ee37e92b to your computer and use it in GitHub Desktop.
Parse html style string for a react component
/**
* @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],
}), {});
@JoshuaSoileau
Copy link

👍 this is helpful, thank you

@SandalovAV
Copy link

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())

@DantSu
Copy link

DantSu commented Feb 5, 2021

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